blob: f64881c1dc7a3016e345ac856cd087386e92d53b [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 Silvermanf51499a2020-09-21 12:49:08 -070045 DetachedBufferWriter(std::string_view filename,
46 std::unique_ptr<DetachedBufferEncoder> encoder);
Austin Schuh2f8fd752020-09-01 22:38:28 -070047 DetachedBufferWriter(DetachedBufferWriter &&other);
48 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
49
Austin Schuha36c8902019-12-30 18:07:15 -080050 ~DetachedBufferWriter();
51
Austin Schuh2f8fd752020-09-01 22:38:28 -070052 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070053 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
54
Austin Schuh6f3babe2020-01-26 20:34:50 -080055 std::string_view filename() const { return filename_; }
56
Austin Schuh2f8fd752020-09-01 22:38:28 -070057 // Rewrites a location in a file (relative to the start) to have new data in
58 // it. The main use case is updating start times after a log file starts.
59 void RewriteLocation(off64_t offset, absl::Span<const uint8_t> data);
60
Brian Silvermanf51499a2020-09-21 12:49:08 -070061 // Queues up a finished FlatBufferBuilder to be encoded and written.
62 //
63 // Triggers a flush if there's enough data queued up.
64 //
65 // Steals the detached buffer from it.
66 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb) {
67 QueueSizedFlatbuffer(fbb->Release());
68 }
69 // May steal the backing storage of buffer, or may leave it alone.
70 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
71 encoder_->Encode(std::move(buffer));
72 FlushAtThreshold();
73 }
Austin Schuha36c8902019-12-30 18:07:15 -080074
Brian Silvermanf51499a2020-09-21 12:49:08 -070075 // Queues up data in span. May copy or may write it to disk immediately.
76 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080077
Brian Silvermanf51499a2020-09-21 12:49:08 -070078 // Returns the total number of bytes written and currently queued.
79 size_t total_bytes() const { return encoder_->total_bytes(); }
Austin Schuha36c8902019-12-30 18:07:15 -080080
Brian Silvermanf51499a2020-09-21 12:49:08 -070081 // The maximum time for a single write call, or 0 if none have been performed.
82 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
83 // The number of bytes in the longest write call, or -1 if none have been
84 // performed.
85 int max_write_time_bytes() const { return max_write_time_bytes_; }
86 // The number of buffers in the longest write call, or -1 if none have been
87 // performed.
88 int max_write_time_messages() const { return max_write_time_messages_; }
89 // The total time spent in write calls.
90 std::chrono::nanoseconds total_write_time() const {
91 return total_write_time_;
92 }
93 // The total number of writes which have been performed.
94 int total_write_count() const { return total_write_count_; }
95 // The total number of messages which have been written.
96 int total_write_messages() const { return total_write_messages_; }
97 // The total number of bytes which have been written.
98 int total_write_bytes() const { return total_write_bytes_; }
99 void ResetStatistics() {
100 max_write_time_ = std::chrono::nanoseconds::zero();
101 max_write_time_bytes_ = -1;
102 max_write_time_messages_ = -1;
103 total_write_time_ = std::chrono::nanoseconds::zero();
104 total_write_count_ = 0;
105 total_write_messages_ = 0;
106 total_write_bytes_ = 0;
107 }
Brian Silverman98360e22020-04-28 16:51:20 -0700108
Austin Schuha36c8902019-12-30 18:07:15 -0800109 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700110 // Performs a single writev call with as much of the data we have queued up as
111 // possible.
112 //
113 // This will normally take all of the data we have queued up, unless an
114 // encoder has spit out a big enough chunk all at once that we can't manage
115 // all of it.
116 void Flush();
117
118 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
119 ssize_t written, int iovec_size);
120
121 // Flushes data if we've reached the threshold to do that as part of normal
122 // operation.
123 void FlushAtThreshold();
124
Austin Schuh2f8fd752020-09-01 22:38:28 -0700125 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700126 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800127
Austin Schuha36c8902019-12-30 18:07:15 -0800128 int fd_ = -1;
129
Austin Schuha36c8902019-12-30 18:07:15 -0800130 // List of iovecs to use with writev. This is a member variable to avoid
131 // churn.
132 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700133
134 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
135 int max_write_time_bytes_ = -1;
136 int max_write_time_messages_ = -1;
137 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
138 int total_write_count_ = 0;
139 int total_write_messages_ = 0;
140 int total_write_bytes_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -0800141};
142
143// Packes a message pointed to by the context into a MessageHeader.
144flatbuffers::Offset<MessageHeader> PackMessage(
145 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
146 int channel_index, LogType log_type);
147
Austin Schuh6f3babe2020-01-26 20:34:50 -0800148FlatbufferVector<LogFileHeader> ReadHeader(std::string_view filename);
Austin Schuh5212cad2020-09-09 23:12:09 -0700149FlatbufferVector<MessageHeader> ReadNthMessage(std::string_view filename,
150 size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800151
Austin Schuh05b70472020-01-01 17:11:17 -0800152// Class to read chunks out of a log file.
153class SpanReader {
154 public:
155 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800156
Austin Schuh6f3babe2020-01-26 20:34:50 -0800157 std::string_view filename() const { return filename_; }
158
Austin Schuh05b70472020-01-01 17:11:17 -0800159 // Returns a span with the data for a message from the log file, excluding
160 // the size.
161 absl::Span<const uint8_t> ReadMessage();
162
163 // Returns true if there is a full message available in the buffer, or if we
164 // will have to read more data from disk.
165 bool MessageAvailable();
166
167 private:
168 // TODO(austin): Optimization:
169 // Allocate the 256k blocks like we do today. But, refcount them with
170 // shared_ptr pointed to by the messageheader that is returned. This avoids
171 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700172 // And (Brian): Consider just mmapping the file and handing out refcounted
173 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800174
175 // Reads a chunk of data into data_. Returns false if no data was read.
176 bool ReadBlock();
177
Austin Schuh6f3babe2020-01-26 20:34:50 -0800178 const std::string filename_;
179
Brian Silvermanf51499a2020-09-21 12:49:08 -0700180 // File reader and data decoder.
181 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800182
Brian Silvermanf51499a2020-09-21 12:49:08 -0700183 // Vector to read into.
184 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800185
186 // Amount of data consumed already in data_.
187 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800188};
189
190// Class which handles reading the header and messages from the log file. This
191// handles any per-file state left before merging below.
192class MessageReader {
193 public:
194 MessageReader(std::string_view filename);
195
Austin Schuh6f3babe2020-01-26 20:34:50 -0800196 std::string_view filename() const { return span_reader_.filename(); }
197
Austin Schuh05b70472020-01-01 17:11:17 -0800198 // Returns the header from the log file.
199 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700200 return &raw_log_file_header_.message();
201 }
202
203 // Returns the raw data of the header from the log file.
204 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
205 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800206 }
207
208 // Returns the minimum maount of data needed to queue up for sorting before
209 // ware guarenteed to not see data out of order.
210 std::chrono::nanoseconds max_out_of_order_duration() const {
211 return max_out_of_order_duration_;
212 }
213
Austin Schuhcde938c2020-02-02 17:30:07 -0800214 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800215 monotonic_clock::time_point newest_timestamp() const {
216 return newest_timestamp_;
217 }
218
219 // Returns the next message if there is one.
220 std::optional<FlatbufferVector<MessageHeader>> ReadMessage();
221
222 // The time at which we need to read another chunk from the logfile.
223 monotonic_clock::time_point queue_data_time() const {
224 return newest_timestamp() - max_out_of_order_duration();
225 }
226
227 private:
228 // Log chunk reader.
229 SpanReader span_reader_;
230
Austin Schuh97789fc2020-08-01 14:42:45 -0700231 // Vector holding the raw data for the log file header.
232 FlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800233
234 // Minimum amount of data to queue up for sorting before we are guarenteed
235 // to not see data out of order.
236 std::chrono::nanoseconds max_out_of_order_duration_;
237
238 // Timestamp of the newest message in a channel queue.
239 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
240};
241
Austin Schuh6f3babe2020-01-26 20:34:50 -0800242class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800243
Austin Schuh6f3babe2020-01-26 20:34:50 -0800244// A design requirement is that the relevant data for a channel is not more than
245// max_out_of_order_duration out of order. We approach sorting in layers.
246//
247// 1) Split each (maybe chunked) log file into one queue per channel. Read this
248// log file looking for data pertaining to a specific node.
249// (SplitMessageReader)
250// 2) Merge all the data per channel from the different log files into a sorted
251// list of timestamps and messages. (TimestampMerger)
252// 3) Combine the timestamps and messages. (TimestampMerger)
253// 4) Merge all the channels to produce the next message on a node.
254// (ChannelMerger)
255// 5) Duplicate this entire stack per node.
256
257// This class splits messages and timestamps up into a queue per channel, and
258// handles reading data from multiple chunks.
259class SplitMessageReader {
260 public:
261 SplitMessageReader(const std::vector<std::string> &filenames);
262
263 // Sets the TimestampMerger that gets notified for each channel. The node
264 // that the TimestampMerger is merging as needs to be passed in.
265 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
266 const Node *target_node);
267
Austin Schuh2f8fd752020-09-01 22:38:28 -0700268 // Returns the (timestamp, queue_index, message_header) for the oldest message
269 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800270 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
271 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800272 return channels_[channel].data.front_timestamp();
273 }
274
Austin Schuh2f8fd752020-09-01 22:38:28 -0700275 // Returns the (timestamp, queue_index, message_header) for the oldest
276 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800277 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
278 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800279 return channels_[channel].timestamps[destination_node].front_timestamp();
280 }
281
282 // Returns the timestamp, queue_index, and message for the oldest data on a
283 // channel. Requeues data as needed.
284 std::tuple<monotonic_clock::time_point, uint32_t,
285 FlatbufferVector<MessageHeader>>
286 PopOldest(int channel_index);
287
288 // Returns the timestamp, queue_index, and message for the oldest timestamp on
289 // a channel delivered to a node. Requeues data as needed.
290 std::tuple<monotonic_clock::time_point, uint32_t,
291 FlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700292 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800293
294 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800295 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800296 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800297 }
298
Austin Schuh97789fc2020-08-01 14:42:45 -0700299 const FlatbufferVector<LogFileHeader> &raw_log_file_header() const {
300 return log_file_header_;
301 }
302
Austin Schuh6f3babe2020-01-26 20:34:50 -0800303 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800304 monotonic_clock::time_point monotonic_start_time() {
305 return monotonic_clock::time_point(
306 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
307 }
308 realtime_clock::time_point realtime_start_time() {
309 return realtime_clock::time_point(
310 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
311 }
312
Austin Schuh6f3babe2020-01-26 20:34:50 -0800313 // Returns the configuration from the log file header.
314 const Configuration *configuration() const {
315 return log_file_header()->configuration();
316 }
317
Austin Schuh05b70472020-01-01 17:11:17 -0800318 // Returns the node who's point of view this log file is from. Make sure this
319 // is a pointer in the configuration() nodes list so it can be consumed
320 // elsewhere.
321 const Node *node() const {
322 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800323 return configuration::GetNodeOrDie(configuration(),
324 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800325 } else {
326 CHECK(!log_file_header()->has_node());
327 return nullptr;
328 }
329 }
330
Austin Schuh6f3babe2020-01-26 20:34:50 -0800331 // Returns the timestamp of the newest message read from the log file, and the
332 // timestamp that we need to re-queue data.
333 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800334 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800335 }
336
Austin Schuhcde938c2020-02-02 17:30:07 -0800337 // Returns the next time to trigger a requeue.
338 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
339
340 // Returns the minimum amount of data needed to queue up for sorting before
341 // ware guarenteed to not see data out of order.
342 std::chrono::nanoseconds max_out_of_order_duration() const {
343 return message_reader_->max_out_of_order_duration();
344 }
345
346 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800347
348 // Adds more messages to the sorted list. This reads enough data such that
349 // oldest_message_time can be replayed safely. Returns false if the log file
350 // has all been read.
351 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800352
Austin Schuhcde938c2020-02-02 17:30:07 -0800353 // Returns debug strings for a channel, and timestamps for a node.
354 std::string DebugString(int channel) const;
355 std::string DebugString(int channel, int node_index) const;
356
Austin Schuh8bd96322020-02-13 21:18:22 -0800357 // Returns true if all the messages have been queued from the last log file in
358 // the list of log files chunks.
359 bool at_end() const { return at_end_; }
360
Austin Schuh05b70472020-01-01 17:11:17 -0800361 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800362 // TODO(austin): Need to copy or refcount the message instead of running
363 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
364 // inside.
365
Austin Schuhfa895892020-01-07 20:07:41 -0800366 // Moves to the next log file in the list.
367 bool NextLogFile();
368
Austin Schuh6f3babe2020-01-26 20:34:50 -0800369 // Filenames of the log files.
370 std::vector<std::string> filenames_;
371 // And the index of the next file to open.
372 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800373
Austin Schuhee711052020-08-24 16:06:09 -0700374 // Node we are reading as.
375 const Node *target_node_ = nullptr;
376
Austin Schuh6f3babe2020-01-26 20:34:50 -0800377 // Log file header to report. This is a copy.
Austin Schuh97789fc2020-08-01 14:42:45 -0700378 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800379 // Current log file being read.
380 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800381
382 // Datastructure to hold the list of messages, cached timestamp for the
383 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800384 struct MessageHeaderQueue {
385 // If true, this is a timestamp queue.
386 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800387
Austin Schuh6f3babe2020-01-26 20:34:50 -0800388 // Returns a reference to the the oldest message.
389 FlatbufferVector<MessageHeader> &front() {
390 CHECK_GT(data_.size(), 0u);
391 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800392 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800393
Austin Schuhcde938c2020-02-02 17:30:07 -0800394 // Adds a message to the back of the queue. Returns true if it was actually
395 // emplaced.
396 bool emplace_back(FlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800397
398 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700399 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800400
401 // The size of the queue.
402 size_t size() { return data_.size(); }
403
Austin Schuhcde938c2020-02-02 17:30:07 -0800404 // Returns a debug string with info about each message in the queue.
405 std::string DebugString() const;
406
Austin Schuh2f8fd752020-09-01 22:38:28 -0700407 // Returns the (timestamp, queue_index, message_header) for the oldest
408 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800409 const std::tuple<monotonic_clock::time_point, uint32_t,
410 const MessageHeader *>
411 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700412 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800413 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700414 monotonic_clock::time_point(
415 std::chrono::nanoseconds(message.monotonic_sent_time())),
416 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800417 }
418
419 // Pointer to the timestamp merger for this queue if available.
420 TimestampMerger *timestamp_merger = nullptr;
421 // Pointer to the reader which feeds this queue.
422 SplitMessageReader *split_reader = nullptr;
423
424 private:
425 // The data.
426 std::deque<FlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800427 };
428
Austin Schuh6f3babe2020-01-26 20:34:50 -0800429 // All the queues needed for a channel. There isn't going to be data in all
430 // of these.
431 struct ChannelData {
432 // The data queue for the channel.
433 MessageHeaderQueue data;
434 // Queues for timestamps for each node.
435 std::vector<MessageHeaderQueue> timestamps;
436 };
Austin Schuhfa895892020-01-07 20:07:41 -0800437
Austin Schuh6f3babe2020-01-26 20:34:50 -0800438 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800439 std::vector<ChannelData> channels_;
440
Austin Schuh6f3babe2020-01-26 20:34:50 -0800441 // Once we know the node that this SplitMessageReader will be writing as,
442 // there will be only one MessageHeaderQueue that a specific channel matches.
443 // Precompute this here for efficiency.
444 std::vector<MessageHeaderQueue *> channels_to_write_;
445
Austin Schuhcde938c2020-02-02 17:30:07 -0800446 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
447
448 // Latches true when we hit the end of the last log file and there is no sense
449 // poking it further.
450 bool at_end_ = false;
451
452 // Timestamp of the newest message that was read and actually queued. We want
453 // to track this independently from the log file because we need the
454 // timestamps here to be timestamps of messages that are queued.
455 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800456};
457
458class ChannelMerger;
459
460// Sorts channels (and timestamps) from multiple log files for a single channel.
461class TimestampMerger {
462 public:
463 TimestampMerger(const Configuration *configuration,
464 std::vector<SplitMessageReader *> split_message_readers,
465 int channel_index, const Node *target_node,
466 ChannelMerger *channel_merger);
467
468 // Metadata used to schedule the message.
469 struct DeliveryTimestamp {
470 monotonic_clock::time_point monotonic_event_time =
471 monotonic_clock::min_time;
472 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
473
474 monotonic_clock::time_point monotonic_remote_time =
475 monotonic_clock::min_time;
476 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
477 uint32_t remote_queue_index = 0xffffffff;
478 };
479
480 // Pushes SplitMessageReader onto the timestamp heap. This should only be
481 // called when timestamps are placed in the channel this class is merging for
482 // the reader.
483 void UpdateTimestamp(
484 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800485 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
486 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800487 PushTimestampHeap(oldest_message_time, split_message_reader);
488 }
489 // Pushes SplitMessageReader onto the message heap. This should only be
490 // called when data is placed in the channel this class is merging for the
491 // reader.
492 void Update(
493 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800494 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
495 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800496 PushMessageHeap(oldest_message_time, split_message_reader);
497 }
498
Austin Schuhcde938c2020-02-02 17:30:07 -0800499 // Returns the oldest combined timestamp and data for this channel. If there
500 // isn't a matching piece of data, returns only the timestamp with no data.
501 // The caller can determine what the appropriate action is to recover.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800502 std::tuple<DeliveryTimestamp, FlatbufferVector<MessageHeader>> PopOldest();
503
504 // Tracks if the channel merger has pushed this onto it's heap or not.
505 bool pushed() { return pushed_; }
506 // Sets if this has been pushed to the channel merger heap. Should only be
507 // called by the channel merger.
508 void set_pushed(bool pushed) { pushed_ = pushed; }
509
Austin Schuhcde938c2020-02-02 17:30:07 -0800510 // Returns a debug string with the heaps printed out.
511 std::string DebugString() const;
512
Austin Schuh8bd96322020-02-13 21:18:22 -0800513 // Returns true if we have timestamps.
514 bool has_timestamps() const { return has_timestamps_; }
515
516 // Records that one of the log files ran out of data. This should only be
517 // called by a SplitMessageReader.
518 void NoticeAtEnd();
519
Austin Schuh2f8fd752020-09-01 22:38:28 -0700520 aos::monotonic_clock::time_point channel_merger_time() {
521 if (has_timestamps_) {
522 return std::get<0>(timestamp_heap_[0]);
523 } else {
524 return std::get<0>(message_heap_[0]);
525 }
526 }
527
Austin Schuh6f3babe2020-01-26 20:34:50 -0800528 private:
529 // Pushes messages and timestamps to the corresponding heaps.
530 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800531 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
532 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800533 SplitMessageReader *split_message_reader);
534 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800535 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
536 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800537 SplitMessageReader *split_message_reader);
538
539 // Pops a message from the message heap. This automatically triggers the
540 // split message reader to re-fetch any new data.
541 std::tuple<monotonic_clock::time_point, uint32_t,
542 FlatbufferVector<MessageHeader>>
543 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800544
545 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
546 oldest_message() const;
547 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
548 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800549 // Pops a message from the timestamp heap. This automatically triggers the
550 // split message reader to re-fetch any new data.
551 std::tuple<monotonic_clock::time_point, uint32_t,
552 FlatbufferVector<MessageHeader>>
553 PopTimestampHeap();
554
555 const Configuration *configuration_;
556
557 // If true, this is a forwarded channel and timestamps should be matched.
558 bool has_timestamps_ = false;
559
560 // Tracks if the ChannelMerger has pushed this onto it's queue.
561 bool pushed_ = false;
562
563 // The split message readers used for source data.
564 std::vector<SplitMessageReader *> split_message_readers_;
565
566 // The channel to merge.
567 int channel_index_;
568
569 // Our node.
570 int node_index_;
571
572 // Heaps for messages and timestamps.
573 std::vector<
574 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
575 message_heap_;
576 std::vector<
577 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
578 timestamp_heap_;
579
580 // Parent channel merger.
581 ChannelMerger *channel_merger_;
582};
583
584// This class handles constructing all the split message readers, channel
585// mergers, and combining the results.
586class ChannelMerger {
587 public:
588 // Builds a ChannelMerger around a set of log files. These are of the format:
589 // {
590 // {log1_part0, log1_part1, ...},
591 // {log2}
592 // }
593 // The inner vector is a list of log file chunks which form up a log file.
594 // The outer vector is a list of log files with subsets of the messages, or
595 // messages from different nodes.
596 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
597
598 // Returns the nodes that we know how to merge.
599 const std::vector<const Node *> nodes() const;
600 // Sets the node that we will return messages as. Returns true if the node
601 // has log files and will produce data. This can only be called once, and
602 // will likely corrupt state if called a second time.
603 bool SetNode(const Node *target_node);
604
605 // Everything else needs the node set before it works.
606
607 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700608 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800609 // Pops the oldest message.
610 std::tuple<TimestampMerger::DeliveryTimestamp, int,
611 FlatbufferVector<MessageHeader>>
612 PopOldest();
613
614 // Returns the config for this set of log files.
615 const Configuration *configuration() const {
616 return log_file_header()->configuration();
617 }
618
619 const LogFileHeader *log_file_header() const {
620 return &log_file_header_.message();
621 }
622
623 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800624 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800625 return monotonic_clock::time_point(
626 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
627 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800628 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800629 return realtime_clock::time_point(
630 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
631 }
632
633 // Returns the node set by SetNode above.
634 const Node *node() const { return node_; }
635
636 // Called by the TimestampMerger when new data is available with the provided
637 // timestamp and channel_index.
638 void Update(monotonic_clock::time_point timestamp, int channel_index) {
639 PushChannelHeap(timestamp, channel_index);
640 }
641
Austin Schuhcde938c2020-02-02 17:30:07 -0800642 // Returns a debug string with all the heaps in it. Generally only useful for
643 // debugging what went wrong.
644 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800645
Austin Schuh8bd96322020-02-13 21:18:22 -0800646 // Returns true if one of the log files has finished reading everything. When
647 // log file chunks are involved, this means that the last chunk in a log file
648 // has been read. It is acceptable to be missing data at this point in time.
649 bool at_end() const { return at_end_; }
650
651 // Marks that one of the log files is at the end. This should only be called
652 // by timestamp mergers.
653 void NoticeAtEnd() { at_end_ = true; }
654
Austin Schuhcde938c2020-02-02 17:30:07 -0800655 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800656 // Pushes the timestamp for new data on the provided channel.
657 void PushChannelHeap(monotonic_clock::time_point timestamp,
658 int channel_index);
659
Austin Schuh2f8fd752020-09-01 22:38:28 -0700660 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
661 void VerifyHeaps();
662
Austin Schuh6f3babe2020-01-26 20:34:50 -0800663 // All the message readers.
664 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
665
666 // The log header we are claiming to be.
Austin Schuh97789fc2020-08-01 14:42:45 -0700667 FlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800668
669 // The timestamp mergers which combine data from the split message readers.
670 std::vector<TimestampMerger> timestamp_mergers_;
671
672 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800673 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
674
Austin Schuh6f3babe2020-01-26 20:34:50 -0800675 // Configured node.
676 const Node *node_;
677
Austin Schuh8bd96322020-02-13 21:18:22 -0800678 bool at_end_ = false;
679
Austin Schuh6f3babe2020-01-26 20:34:50 -0800680 // Cached copy of the list of nodes.
681 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700682
683 // Last time popped. Used to detect events being returned out of order.
684 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800685};
Austin Schuha36c8902019-12-30 18:07:15 -0800686
Austin Schuhee711052020-08-24 16:06:09 -0700687// Returns the node name with a trailing space, or an empty string if we are on
688// a single node.
689std::string MaybeNodeName(const Node *);
690
Brian Silvermanf51499a2020-09-21 12:49:08 -0700691} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800692
693#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_