blob: 985a6bca01e55d9129296746c02214ec0afd6b3e [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#ifndef AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_
2#define AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_
3
4#include <sys/uio.h>
5
Austin Schuh97789fc2020-08-01 14:42:45 -07006#include <chrono>
Austin Schuh05b70472020-01-01 17:11:17 -08007#include <deque>
Austin Schuh97789fc2020-08-01 14:42:45 -07008#include <limits>
9#include <memory>
Austin Schuh05b70472020-01-01 17:11:17 -080010#include <optional>
Austin Schuhfa895892020-01-07 20:07:41 -080011#include <string>
Austin Schuha36c8902019-12-30 18:07:15 -080012#include <string_view>
Brian Silverman98360e22020-04-28 16:51:20 -070013#include <tuple>
Austin Schuh97789fc2020-08-01 14:42:45 -070014#include <utility>
Austin Schuha36c8902019-12-30 18:07:15 -080015#include <vector>
16
Austin Schuh05b70472020-01-01 17:11:17 -080017#include "absl/types/span.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070018#include "aos/containers/resizeable_buffer.h"
Austin Schuha36c8902019-12-30 18:07:15 -080019#include "aos/events/event_loop.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070020#include "aos/events/logging/buffer_encoder.h"
Austin Schuhc41603c2020-10-11 16:17:37 -070021#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080022#include "aos/events/logging/logger_generated.h"
Brian Silvermanf51499a2020-09-21 12:49:08 -070023#include "aos/flatbuffers.h"
Austin Schuha36c8902019-12-30 18:07:15 -080024#include "flatbuffers/flatbuffers.h"
25
Brian Silvermanf51499a2020-09-21 12:49:08 -070026namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080027
28enum class LogType : uint8_t {
29 // The message originated on this node and should be logged here.
30 kLogMessage,
31 // The message originated on another node, but only the delivery times are
32 // logged here.
33 kLogDeliveryTimeOnly,
34 // The message originated on another node. Log it and the delivery times
35 // together. The message_gateway is responsible for logging any messages
36 // which didn't get delivered.
Austin Schuh6f3babe2020-01-26 20:34:50 -080037 kLogMessageAndDeliveryTime,
38 // The message originated on the other node and should be logged on this node.
39 kLogRemoteMessage
Austin Schuha36c8902019-12-30 18:07:15 -080040};
41
Austin Schuha36c8902019-12-30 18:07:15 -080042// This class manages efficiently writing a sequence of detached buffers to a
Brian Silvermanf51499a2020-09-21 12:49:08 -070043// file. It encodes them, queues them up, and batches the write operation.
Austin Schuha36c8902019-12-30 18:07:15 -080044class DetachedBufferWriter {
45 public:
Brian Silvermana9f2ec92020-10-06 18:00:53 -070046 // Marker struct for one of our constructor overloads.
47 struct already_out_of_space_t {};
48
Brian Silvermanf51499a2020-09-21 12:49:08 -070049 DetachedBufferWriter(std::string_view filename,
50 std::unique_ptr<DetachedBufferEncoder> encoder);
Brian Silvermana9f2ec92020-10-06 18:00:53 -070051 // Creates a dummy instance which won't even open a file. It will act as if
52 // opening the file ran out of space immediately.
53 DetachedBufferWriter(already_out_of_space_t) : ran_out_of_space_(true) {}
Austin Schuh2f8fd752020-09-01 22:38:28 -070054 DetachedBufferWriter(DetachedBufferWriter &&other);
55 DetachedBufferWriter(const DetachedBufferWriter &) = delete;
56
Austin Schuha36c8902019-12-30 18:07:15 -080057 ~DetachedBufferWriter();
58
Austin Schuh2f8fd752020-09-01 22:38:28 -070059 DetachedBufferWriter &operator=(DetachedBufferWriter &&other);
Brian Silverman98360e22020-04-28 16:51:20 -070060 DetachedBufferWriter &operator=(const DetachedBufferWriter &) = delete;
61
Austin Schuh6f3babe2020-01-26 20:34:50 -080062 std::string_view filename() const { return filename_; }
63
Brian Silvermana9f2ec92020-10-06 18:00:53 -070064 // This will be true until Close() is called, unless the file couldn't be
65 // created due to running out of space.
66 bool is_open() const { return fd_ != -1; }
67
Brian Silvermanf51499a2020-09-21 12:49:08 -070068 // Queues up a finished FlatBufferBuilder to be encoded and written.
69 //
70 // Triggers a flush if there's enough data queued up.
71 //
72 // Steals the detached buffer from it.
73 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb) {
74 QueueSizedFlatbuffer(fbb->Release());
75 }
76 // May steal the backing storage of buffer, or may leave it alone.
77 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070078 if (ran_out_of_space_) {
79 return;
80 }
Brian Silvermanf51499a2020-09-21 12:49:08 -070081 encoder_->Encode(std::move(buffer));
82 FlushAtThreshold();
83 }
Austin Schuha36c8902019-12-30 18:07:15 -080084
Brian Silvermanf51499a2020-09-21 12:49:08 -070085 // Queues up data in span. May copy or may write it to disk immediately.
86 void QueueSpan(absl::Span<const uint8_t> span);
Austin Schuha36c8902019-12-30 18:07:15 -080087
Brian Silverman0465fcf2020-09-24 00:29:18 -070088 // Indicates we got ENOSPC when trying to write. After this returns true, no
89 // further data is written.
90 bool ran_out_of_space() const { return ran_out_of_space_; }
91
92 // To avoid silently failing to write logfiles, you must call this before
93 // destruction if ran_out_of_space() is true and the situation has been
94 // handled.
95 void acknowledge_out_of_space() {
96 CHECK(ran_out_of_space_);
97 acknowledge_ran_out_of_space_ = true;
98 }
99
100 // Fully flushes and closes the underlying file now. No additional data may be
101 // enqueued after calling this.
102 //
103 // This will be performed in the destructor automatically.
104 //
105 // Note that this may set ran_out_of_space().
106 void Close();
107
Brian Silvermanf51499a2020-09-21 12:49:08 -0700108 // Returns the total number of bytes written and currently queued.
109 size_t total_bytes() const { return encoder_->total_bytes(); }
Austin Schuha36c8902019-12-30 18:07:15 -0800110
Brian Silvermanf51499a2020-09-21 12:49:08 -0700111 // The maximum time for a single write call, or 0 if none have been performed.
112 std::chrono::nanoseconds max_write_time() const { return max_write_time_; }
113 // The number of bytes in the longest write call, or -1 if none have been
114 // performed.
115 int max_write_time_bytes() const { return max_write_time_bytes_; }
116 // The number of buffers in the longest write call, or -1 if none have been
117 // performed.
118 int max_write_time_messages() const { return max_write_time_messages_; }
119 // The total time spent in write calls.
120 std::chrono::nanoseconds total_write_time() const {
121 return total_write_time_;
122 }
123 // The total number of writes which have been performed.
124 int total_write_count() const { return total_write_count_; }
125 // The total number of messages which have been written.
126 int total_write_messages() const { return total_write_messages_; }
127 // The total number of bytes which have been written.
128 int total_write_bytes() const { return total_write_bytes_; }
129 void ResetStatistics() {
130 max_write_time_ = std::chrono::nanoseconds::zero();
131 max_write_time_bytes_ = -1;
132 max_write_time_messages_ = -1;
133 total_write_time_ = std::chrono::nanoseconds::zero();
134 total_write_count_ = 0;
135 total_write_messages_ = 0;
136 total_write_bytes_ = 0;
137 }
Brian Silverman98360e22020-04-28 16:51:20 -0700138
Austin Schuha36c8902019-12-30 18:07:15 -0800139 private:
Brian Silvermanf51499a2020-09-21 12:49:08 -0700140 // Performs a single writev call with as much of the data we have queued up as
141 // possible.
142 //
143 // This will normally take all of the data we have queued up, unless an
144 // encoder has spit out a big enough chunk all at once that we can't manage
145 // all of it.
146 void Flush();
147
Brian Silverman0465fcf2020-09-24 00:29:18 -0700148 // write_return is what write(2) or writev(2) returned. write_size is the
149 // number of bytes we expected it to write.
150 void HandleWriteReturn(ssize_t write_return, size_t write_size);
151
Brian Silvermanf51499a2020-09-21 12:49:08 -0700152 void UpdateStatsForWrite(aos::monotonic_clock::duration duration,
153 ssize_t written, int iovec_size);
154
155 // Flushes data if we've reached the threshold to do that as part of normal
156 // operation.
157 void FlushAtThreshold();
158
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 std::string filename_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700160 std::unique_ptr<DetachedBufferEncoder> encoder_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800161
Austin Schuha36c8902019-12-30 18:07:15 -0800162 int fd_ = -1;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700163 bool ran_out_of_space_ = false;
164 bool acknowledge_ran_out_of_space_ = false;
Austin Schuha36c8902019-12-30 18:07:15 -0800165
Austin Schuha36c8902019-12-30 18:07:15 -0800166 // List of iovecs to use with writev. This is a member variable to avoid
167 // churn.
168 std::vector<struct iovec> iovec_;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700169
170 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
171 int max_write_time_bytes_ = -1;
172 int max_write_time_messages_ = -1;
173 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
174 int total_write_count_ = 0;
175 int total_write_messages_ = 0;
176 int total_write_bytes_ = 0;
Austin Schuha36c8902019-12-30 18:07:15 -0800177};
178
179// Packes a message pointed to by the context into a MessageHeader.
180flatbuffers::Offset<MessageHeader> PackMessage(
181 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
182 int channel_index, LogType log_type);
183
Austin Schuhadd6eb32020-11-09 21:24:26 -0800184std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800185 std::string_view filename);
Austin Schuhadd6eb32020-11-09 21:24:26 -0800186std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800187 std::string_view filename, size_t n);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800188
Austin Schuh05b70472020-01-01 17:11:17 -0800189// Class to read chunks out of a log file.
190class SpanReader {
191 public:
192 SpanReader(std::string_view filename);
Austin Schuha36c8902019-12-30 18:07:15 -0800193
Austin Schuh6f3babe2020-01-26 20:34:50 -0800194 std::string_view filename() const { return filename_; }
195
Austin Schuh05b70472020-01-01 17:11:17 -0800196 // Returns a span with the data for a message from the log file, excluding
197 // the size.
198 absl::Span<const uint8_t> ReadMessage();
199
Austin Schuh05b70472020-01-01 17:11:17 -0800200 private:
201 // TODO(austin): Optimization:
202 // Allocate the 256k blocks like we do today. But, refcount them with
203 // shared_ptr pointed to by the messageheader that is returned. This avoids
204 // the copy. Need to do more benchmarking.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700205 // And (Brian): Consider just mmapping the file and handing out refcounted
206 // pointers into that too.
Austin Schuh05b70472020-01-01 17:11:17 -0800207
208 // Reads a chunk of data into data_. Returns false if no data was read.
209 bool ReadBlock();
210
Austin Schuhc41603c2020-10-11 16:17:37 -0700211 std::string filename_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800212
Brian Silvermanf51499a2020-09-21 12:49:08 -0700213 // File reader and data decoder.
214 std::unique_ptr<DataDecoder> decoder_;
Austin Schuh05b70472020-01-01 17:11:17 -0800215
Brian Silvermanf51499a2020-09-21 12:49:08 -0700216 // Vector to read into.
217 ResizeableBuffer data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800218
219 // Amount of data consumed already in data_.
220 size_t consumed_data_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800221};
222
223// Class which handles reading the header and messages from the log file. This
224// handles any per-file state left before merging below.
225class MessageReader {
226 public:
227 MessageReader(std::string_view filename);
228
Austin Schuh6f3babe2020-01-26 20:34:50 -0800229 std::string_view filename() const { return span_reader_.filename(); }
230
Austin Schuh05b70472020-01-01 17:11:17 -0800231 // Returns the header from the log file.
232 const LogFileHeader *log_file_header() const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700233 return &raw_log_file_header_.message();
234 }
235
236 // Returns the raw data of the header from the log file.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800237 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
238 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700239 return raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800240 }
241
242 // Returns the minimum maount of data needed to queue up for sorting before
243 // ware guarenteed to not see data out of order.
244 std::chrono::nanoseconds max_out_of_order_duration() const {
245 return max_out_of_order_duration_;
246 }
247
Austin Schuhcde938c2020-02-02 17:30:07 -0800248 // Returns the newest timestamp read out of the log file.
Austin Schuh05b70472020-01-01 17:11:17 -0800249 monotonic_clock::time_point newest_timestamp() const {
250 return newest_timestamp_;
251 }
252
253 // Returns the next message if there is one.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800254 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800255
256 // The time at which we need to read another chunk from the logfile.
257 monotonic_clock::time_point queue_data_time() const {
258 return newest_timestamp() - max_out_of_order_duration();
259 }
260
261 private:
262 // Log chunk reader.
263 SpanReader span_reader_;
264
Austin Schuh97789fc2020-08-01 14:42:45 -0700265 // Vector holding the raw data for the log file header.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800266 SizePrefixedFlatbufferVector<LogFileHeader> raw_log_file_header_;
Austin Schuh05b70472020-01-01 17:11:17 -0800267
268 // Minimum amount of data to queue up for sorting before we are guarenteed
269 // to not see data out of order.
270 std::chrono::nanoseconds max_out_of_order_duration_;
271
272 // Timestamp of the newest message in a channel queue.
273 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
274};
275
Austin Schuhc41603c2020-10-11 16:17:37 -0700276// A class to seamlessly read messages from a list of part files.
277class PartsMessageReader {
278 public:
279 PartsMessageReader(LogParts log_parts);
280
281 std::string_view filename() const { return message_reader_.filename(); }
282
283 // Returns the minimum amount of data needed to queue up for sorting before
284 // we are guarenteed to not see data out of order.
285 std::chrono::nanoseconds max_out_of_order_duration() const {
286 return message_reader_.max_out_of_order_duration();
287 }
288
289 // Returns the newest timestamp read out of the log file.
290 monotonic_clock::time_point newest_timestamp() const {
291 return newest_timestamp_;
292 }
293
294 // Returns the next message if there is one, or nullopt if we have reached the
295 // end of all the files.
296 // Note: reading the next message may change the max_out_of_order_duration().
Austin Schuhadd6eb32020-11-09 21:24:26 -0800297 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadMessage();
Austin Schuhc41603c2020-10-11 16:17:37 -0700298
299 private:
300 // Opens the next log and updates message_reader_. Sets done_ if there is
301 // nothing more to do.
302 void NextLog();
303
304 const LogParts parts_;
305 size_t next_part_index_ = 1u;
306 bool done_ = false;
307 MessageReader message_reader_;
308
309 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
310};
311
Austin Schuh6f3babe2020-01-26 20:34:50 -0800312class TimestampMerger;
Austin Schuh05b70472020-01-01 17:11:17 -0800313
Austin Schuh6f3babe2020-01-26 20:34:50 -0800314// A design requirement is that the relevant data for a channel is not more than
315// max_out_of_order_duration out of order. We approach sorting in layers.
316//
317// 1) Split each (maybe chunked) log file into one queue per channel. Read this
318// log file looking for data pertaining to a specific node.
319// (SplitMessageReader)
320// 2) Merge all the data per channel from the different log files into a sorted
321// list of timestamps and messages. (TimestampMerger)
322// 3) Combine the timestamps and messages. (TimestampMerger)
323// 4) Merge all the channels to produce the next message on a node.
324// (ChannelMerger)
325// 5) Duplicate this entire stack per node.
326
327// This class splits messages and timestamps up into a queue per channel, and
328// handles reading data from multiple chunks.
329class SplitMessageReader {
330 public:
331 SplitMessageReader(const std::vector<std::string> &filenames);
332
333 // Sets the TimestampMerger that gets notified for each channel. The node
334 // that the TimestampMerger is merging as needs to be passed in.
335 void SetTimestampMerger(TimestampMerger *timestamp_merger, int channel,
336 const Node *target_node);
337
Austin Schuh2f8fd752020-09-01 22:38:28 -0700338 // Returns the (timestamp, queue_index, message_header) for the oldest message
339 // in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800340 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
341 oldest_message(int channel) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800342 return channels_[channel].data.front_timestamp();
343 }
344
Austin Schuh2f8fd752020-09-01 22:38:28 -0700345 // Returns the (timestamp, queue_index, message_header) for the oldest
346 // delivery time in a channel, or max_time if there is nothing in the channel.
Austin Schuhcde938c2020-02-02 17:30:07 -0800347 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
348 oldest_message(int channel, int destination_node) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800349 return channels_[channel].timestamps[destination_node].front_timestamp();
350 }
351
352 // Returns the timestamp, queue_index, and message for the oldest data on a
353 // channel. Requeues data as needed.
354 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800355 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800356 PopOldest(int channel_index);
357
358 // Returns the timestamp, queue_index, and message for the oldest timestamp on
359 // a channel delivered to a node. Requeues data as needed.
360 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800361 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh2f8fd752020-09-01 22:38:28 -0700362 PopOldestTimestamp(int channel, int node_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800363
364 // Returns the header for the log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800365 const LogFileHeader *log_file_header() const {
Austin Schuhfa895892020-01-07 20:07:41 -0800366 return &log_file_header_.message();
Austin Schuh05b70472020-01-01 17:11:17 -0800367 }
368
Austin Schuhadd6eb32020-11-09 21:24:26 -0800369 const SizePrefixedFlatbufferVector<LogFileHeader> &raw_log_file_header()
370 const {
Austin Schuh97789fc2020-08-01 14:42:45 -0700371 return log_file_header_;
372 }
373
Austin Schuh6f3babe2020-01-26 20:34:50 -0800374 // Returns the starting time for this set of log files.
Austin Schuh05b70472020-01-01 17:11:17 -0800375 monotonic_clock::time_point monotonic_start_time() {
376 return monotonic_clock::time_point(
377 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
378 }
379 realtime_clock::time_point realtime_start_time() {
380 return realtime_clock::time_point(
381 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
382 }
383
Austin Schuh6f3babe2020-01-26 20:34:50 -0800384 // Returns the configuration from the log file header.
385 const Configuration *configuration() const {
386 return log_file_header()->configuration();
387 }
388
Austin Schuh05b70472020-01-01 17:11:17 -0800389 // Returns the node who's point of view this log file is from. Make sure this
390 // is a pointer in the configuration() nodes list so it can be consumed
391 // elsewhere.
392 const Node *node() const {
393 if (configuration()->has_nodes()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800394 return configuration::GetNodeOrDie(configuration(),
395 log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800396 } else {
397 CHECK(!log_file_header()->has_node());
398 return nullptr;
399 }
400 }
401
Austin Schuh6f3babe2020-01-26 20:34:50 -0800402 // Returns the timestamp of the newest message read from the log file, and the
403 // timestamp that we need to re-queue data.
404 monotonic_clock::time_point newest_timestamp() const {
Austin Schuhcde938c2020-02-02 17:30:07 -0800405 return newest_timestamp_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800406 }
407
Austin Schuhcde938c2020-02-02 17:30:07 -0800408 // Returns the next time to trigger a requeue.
409 monotonic_clock::time_point time_to_queue() const { return time_to_queue_; }
410
411 // Returns the minimum amount of data needed to queue up for sorting before
Austin Schuhc41603c2020-10-11 16:17:37 -0700412 // we are guarenteed to not see data out of order.
Austin Schuhcde938c2020-02-02 17:30:07 -0800413 std::chrono::nanoseconds max_out_of_order_duration() const {
414 return message_reader_->max_out_of_order_duration();
415 }
416
417 std::string_view filename() const { return message_reader_->filename(); }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418
419 // Adds more messages to the sorted list. This reads enough data such that
420 // oldest_message_time can be replayed safely. Returns false if the log file
421 // has all been read.
422 bool QueueMessages(monotonic_clock::time_point oldest_message_time);
Austin Schuh05b70472020-01-01 17:11:17 -0800423
Austin Schuhcde938c2020-02-02 17:30:07 -0800424 // Returns debug strings for a channel, and timestamps for a node.
425 std::string DebugString(int channel) const;
426 std::string DebugString(int channel, int node_index) const;
427
Austin Schuh8bd96322020-02-13 21:18:22 -0800428 // Returns true if all the messages have been queued from the last log file in
429 // the list of log files chunks.
430 bool at_end() const { return at_end_; }
431
Austin Schuh05b70472020-01-01 17:11:17 -0800432 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800433 // TODO(austin): Need to copy or refcount the message instead of running
434 // multiple copies of the reader. Or maybe have a "as_node" index and hide it
435 // inside.
436
Austin Schuhfa895892020-01-07 20:07:41 -0800437 // Moves to the next log file in the list.
438 bool NextLogFile();
439
Austin Schuh6f3babe2020-01-26 20:34:50 -0800440 // Filenames of the log files.
441 std::vector<std::string> filenames_;
442 // And the index of the next file to open.
443 size_t next_filename_index_ = 0;
Austin Schuh05b70472020-01-01 17:11:17 -0800444
Austin Schuhee711052020-08-24 16:06:09 -0700445 // Node we are reading as.
446 const Node *target_node_ = nullptr;
447
Austin Schuh6f3babe2020-01-26 20:34:50 -0800448 // Log file header to report. This is a copy.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800449 SizePrefixedFlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800450 // Current log file being read.
451 std::unique_ptr<MessageReader> message_reader_;
Austin Schuh05b70472020-01-01 17:11:17 -0800452
453 // Datastructure to hold the list of messages, cached timestamp for the
454 // oldest message, and sender to send with.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800455 struct MessageHeaderQueue {
456 // If true, this is a timestamp queue.
457 bool timestamps = false;
Austin Schuh05b70472020-01-01 17:11:17 -0800458
Austin Schuh6f3babe2020-01-26 20:34:50 -0800459 // Returns a reference to the the oldest message.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800460 SizePrefixedFlatbufferVector<MessageHeader> &front() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800461 CHECK_GT(data_.size(), 0u);
462 return data_.front();
Austin Schuh05b70472020-01-01 17:11:17 -0800463 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800464
Austin Schuhcde938c2020-02-02 17:30:07 -0800465 // Adds a message to the back of the queue. Returns true if it was actually
466 // emplaced.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800467 bool emplace_back(SizePrefixedFlatbufferVector<MessageHeader> &&msg);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468
469 // Drops the front message. Invalidates the front() reference.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700470 void PopFront();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800471
472 // The size of the queue.
473 size_t size() { return data_.size(); }
474
Austin Schuhcde938c2020-02-02 17:30:07 -0800475 // Returns a debug string with info about each message in the queue.
476 std::string DebugString() const;
477
Austin Schuh2f8fd752020-09-01 22:38:28 -0700478 // Returns the (timestamp, queue_index, message_header) for the oldest
479 // message.
Austin Schuhcde938c2020-02-02 17:30:07 -0800480 const std::tuple<monotonic_clock::time_point, uint32_t,
481 const MessageHeader *>
482 front_timestamp() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700483 const MessageHeader &message = front().message();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800484 return std::make_tuple(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700485 monotonic_clock::time_point(
486 std::chrono::nanoseconds(message.monotonic_sent_time())),
487 message.queue_index(), &message);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800488 }
489
490 // Pointer to the timestamp merger for this queue if available.
491 TimestampMerger *timestamp_merger = nullptr;
492 // Pointer to the reader which feeds this queue.
493 SplitMessageReader *split_reader = nullptr;
494
495 private:
496 // The data.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800497 std::deque<SizePrefixedFlatbufferVector<MessageHeader>> data_;
Austin Schuh05b70472020-01-01 17:11:17 -0800498 };
499
Austin Schuh6f3babe2020-01-26 20:34:50 -0800500 // All the queues needed for a channel. There isn't going to be data in all
501 // of these.
502 struct ChannelData {
503 // The data queue for the channel.
504 MessageHeaderQueue data;
505 // Queues for timestamps for each node.
506 std::vector<MessageHeaderQueue> timestamps;
507 };
Austin Schuhfa895892020-01-07 20:07:41 -0800508
Austin Schuh6f3babe2020-01-26 20:34:50 -0800509 // Data for all the channels.
Austin Schuh05b70472020-01-01 17:11:17 -0800510 std::vector<ChannelData> channels_;
511
Austin Schuh6f3babe2020-01-26 20:34:50 -0800512 // Once we know the node that this SplitMessageReader will be writing as,
513 // there will be only one MessageHeaderQueue that a specific channel matches.
514 // Precompute this here for efficiency.
515 std::vector<MessageHeaderQueue *> channels_to_write_;
516
Austin Schuhcde938c2020-02-02 17:30:07 -0800517 monotonic_clock::time_point time_to_queue_ = monotonic_clock::min_time;
518
519 // Latches true when we hit the end of the last log file and there is no sense
520 // poking it further.
521 bool at_end_ = false;
522
523 // Timestamp of the newest message that was read and actually queued. We want
524 // to track this independently from the log file because we need the
525 // timestamps here to be timestamps of messages that are queued.
526 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800527};
528
529class ChannelMerger;
530
531// Sorts channels (and timestamps) from multiple log files for a single channel.
532class TimestampMerger {
533 public:
534 TimestampMerger(const Configuration *configuration,
535 std::vector<SplitMessageReader *> split_message_readers,
536 int channel_index, const Node *target_node,
537 ChannelMerger *channel_merger);
538
539 // Metadata used to schedule the message.
540 struct DeliveryTimestamp {
541 monotonic_clock::time_point monotonic_event_time =
542 monotonic_clock::min_time;
543 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700544 uint32_t queue_index = 0xffffffff;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800545
546 monotonic_clock::time_point monotonic_remote_time =
547 monotonic_clock::min_time;
548 realtime_clock::time_point realtime_remote_time = realtime_clock::min_time;
549 uint32_t remote_queue_index = 0xffffffff;
550 };
551
552 // Pushes SplitMessageReader onto the timestamp heap. This should only be
553 // called when timestamps are placed in the channel this class is merging for
554 // the reader.
555 void UpdateTimestamp(
556 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800557 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
558 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800559 PushTimestampHeap(oldest_message_time, split_message_reader);
560 }
561 // Pushes SplitMessageReader onto the message heap. This should only be
562 // called when data is placed in the channel this class is merging for the
563 // reader.
564 void Update(
565 SplitMessageReader *split_message_reader,
Austin Schuhcde938c2020-02-02 17:30:07 -0800566 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
567 oldest_message_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800568 PushMessageHeap(oldest_message_time, split_message_reader);
569 }
570
Austin Schuhcde938c2020-02-02 17:30:07 -0800571 // Returns the oldest combined timestamp and data for this channel. If there
572 // isn't a matching piece of data, returns only the timestamp with no data.
573 // The caller can determine what the appropriate action is to recover.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800574 std::tuple<DeliveryTimestamp, SizePrefixedFlatbufferVector<MessageHeader>>
575 PopOldest();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800576
577 // Tracks if the channel merger has pushed this onto it's heap or not.
578 bool pushed() { return pushed_; }
579 // Sets if this has been pushed to the channel merger heap. Should only be
580 // called by the channel merger.
581 void set_pushed(bool pushed) { pushed_ = pushed; }
582
Austin Schuhcde938c2020-02-02 17:30:07 -0800583 // Returns a debug string with the heaps printed out.
584 std::string DebugString() const;
585
Austin Schuh8bd96322020-02-13 21:18:22 -0800586 // Returns true if we have timestamps.
587 bool has_timestamps() const { return has_timestamps_; }
588
589 // Records that one of the log files ran out of data. This should only be
590 // called by a SplitMessageReader.
591 void NoticeAtEnd();
592
Austin Schuh2f8fd752020-09-01 22:38:28 -0700593 aos::monotonic_clock::time_point channel_merger_time() {
594 if (has_timestamps_) {
595 return std::get<0>(timestamp_heap_[0]);
596 } else {
597 return std::get<0>(message_heap_[0]);
598 }
599 }
600
Austin Schuh6f3babe2020-01-26 20:34:50 -0800601 private:
602 // Pushes messages and timestamps to the corresponding heaps.
603 void PushMessageHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800604 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
605 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800606 SplitMessageReader *split_message_reader);
607 void PushTimestampHeap(
Austin Schuhcde938c2020-02-02 17:30:07 -0800608 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
609 timestamp,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800610 SplitMessageReader *split_message_reader);
611
612 // Pops a message from the message heap. This automatically triggers the
613 // split message reader to re-fetch any new data.
614 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800615 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800616 PopMessageHeap();
Austin Schuhcde938c2020-02-02 17:30:07 -0800617
618 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
619 oldest_message() const;
620 std::tuple<monotonic_clock::time_point, uint32_t, const MessageHeader *>
621 oldest_timestamp() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800622 // Pops a message from the timestamp heap. This automatically triggers the
623 // split message reader to re-fetch any new data.
624 std::tuple<monotonic_clock::time_point, uint32_t,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800625 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800626 PopTimestampHeap();
627
628 const Configuration *configuration_;
629
630 // If true, this is a forwarded channel and timestamps should be matched.
631 bool has_timestamps_ = false;
632
633 // Tracks if the ChannelMerger has pushed this onto it's queue.
634 bool pushed_ = false;
635
636 // The split message readers used for source data.
637 std::vector<SplitMessageReader *> split_message_readers_;
638
639 // The channel to merge.
640 int channel_index_;
641
642 // Our node.
643 int node_index_;
644
645 // Heaps for messages and timestamps.
646 std::vector<
647 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
648 message_heap_;
649 std::vector<
650 std::tuple<monotonic_clock::time_point, uint32_t, SplitMessageReader *>>
651 timestamp_heap_;
652
653 // Parent channel merger.
654 ChannelMerger *channel_merger_;
655};
656
657// This class handles constructing all the split message readers, channel
658// mergers, and combining the results.
659class ChannelMerger {
660 public:
661 // Builds a ChannelMerger around a set of log files. These are of the format:
662 // {
663 // {log1_part0, log1_part1, ...},
664 // {log2}
665 // }
666 // The inner vector is a list of log file chunks which form up a log file.
667 // The outer vector is a list of log files with subsets of the messages, or
668 // messages from different nodes.
669 ChannelMerger(const std::vector<std::vector<std::string>> &filenames);
670
671 // Returns the nodes that we know how to merge.
672 const std::vector<const Node *> nodes() const;
673 // Sets the node that we will return messages as. Returns true if the node
674 // has log files and will produce data. This can only be called once, and
675 // will likely corrupt state if called a second time.
676 bool SetNode(const Node *target_node);
677
678 // Everything else needs the node set before it works.
679
680 // Returns a timestamp for the oldest message in this group of logfiles.
Austin Schuh858c9f32020-08-31 16:56:12 -0700681 monotonic_clock::time_point OldestMessageTime() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800682 // Pops the oldest message.
683 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuhadd6eb32020-11-09 21:24:26 -0800684 SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuh6f3babe2020-01-26 20:34:50 -0800685 PopOldest();
686
687 // Returns the config for this set of log files.
688 const Configuration *configuration() const {
689 return log_file_header()->configuration();
690 }
691
692 const LogFileHeader *log_file_header() const {
693 return &log_file_header_.message();
694 }
695
696 // Returns the start times for the configured node's log files.
Austin Schuhcde938c2020-02-02 17:30:07 -0800697 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800698 return monotonic_clock::time_point(
699 std::chrono::nanoseconds(log_file_header()->monotonic_start_time()));
700 }
Austin Schuhcde938c2020-02-02 17:30:07 -0800701 realtime_clock::time_point realtime_start_time() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800702 return realtime_clock::time_point(
703 std::chrono::nanoseconds(log_file_header()->realtime_start_time()));
704 }
705
706 // Returns the node set by SetNode above.
707 const Node *node() const { return node_; }
708
709 // Called by the TimestampMerger when new data is available with the provided
710 // timestamp and channel_index.
711 void Update(monotonic_clock::time_point timestamp, int channel_index) {
712 PushChannelHeap(timestamp, channel_index);
713 }
714
Austin Schuhcde938c2020-02-02 17:30:07 -0800715 // Returns a debug string with all the heaps in it. Generally only useful for
716 // debugging what went wrong.
717 std::string DebugString() const;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800718
Austin Schuh8bd96322020-02-13 21:18:22 -0800719 // Returns true if one of the log files has finished reading everything. When
720 // log file chunks are involved, this means that the last chunk in a log file
721 // has been read. It is acceptable to be missing data at this point in time.
722 bool at_end() const { return at_end_; }
723
724 // Marks that one of the log files is at the end. This should only be called
725 // by timestamp mergers.
726 void NoticeAtEnd() { at_end_ = true; }
727
Austin Schuhcde938c2020-02-02 17:30:07 -0800728 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800729 // Pushes the timestamp for new data on the provided channel.
730 void PushChannelHeap(monotonic_clock::time_point timestamp,
731 int channel_index);
732
Austin Schuh2f8fd752020-09-01 22:38:28 -0700733 // CHECKs that channel_heap_ and timestamp_heap_ are valid heaps.
734 void VerifyHeaps();
735
Austin Schuh6f3babe2020-01-26 20:34:50 -0800736 // All the message readers.
737 std::vector<std::unique_ptr<SplitMessageReader>> split_message_readers_;
738
739 // The log header we are claiming to be.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800740 SizePrefixedFlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800741
742 // The timestamp mergers which combine data from the split message readers.
743 std::vector<TimestampMerger> timestamp_mergers_;
744
745 // A heap of the channel readers and timestamps for the oldest data in each.
Austin Schuh05b70472020-01-01 17:11:17 -0800746 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
747
Austin Schuh6f3babe2020-01-26 20:34:50 -0800748 // Configured node.
749 const Node *node_;
750
Austin Schuh8bd96322020-02-13 21:18:22 -0800751 bool at_end_ = false;
752
Austin Schuh6f3babe2020-01-26 20:34:50 -0800753 // Cached copy of the list of nodes.
754 std::vector<const Node *> nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700755
756 // Last time popped. Used to detect events being returned out of order.
757 monotonic_clock::time_point last_popped_time_ = monotonic_clock::min_time;
Austin Schuh05b70472020-01-01 17:11:17 -0800758};
Austin Schuha36c8902019-12-30 18:07:15 -0800759
Austin Schuhee711052020-08-24 16:06:09 -0700760// Returns the node name with a trailing space, or an empty string if we are on
761// a single node.
762std::string MaybeNodeName(const Node *);
763
Brian Silvermanf51499a2020-09-21 12:49:08 -0700764} // namespace aos::logger
Austin Schuha36c8902019-12-30 18:07:15 -0800765
766#endif // AOS_EVENTS_LOGGING_LOGFILE_UTILS_H_