blob: d042f90203e29130c334ae5cb9dce499fe55d45b [file] [log] [blame]
Austin Schuhe309d2a2019-11-29 13:25:21 -08001#ifndef AOS_EVENTS_LOGGER_H_
2#define AOS_EVENTS_LOGGER_H_
3
Austin Schuh8bd96322020-02-13 21:18:22 -08004#include <chrono>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <deque>
Austin Schuh05b70472020-01-01 17:11:17 -08006#include <string_view>
Austin Schuh2f8fd752020-09-01 22:38:28 -07007#include <tuple>
Austin Schuh6f3babe2020-01-26 20:34:50 -08008#include <vector>
Austin Schuhe309d2a2019-11-29 13:25:21 -08009
Austin Schuh8bd96322020-02-13 21:18:22 -080010#include "Eigen/Dense"
11#include "absl/strings/str_cat.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070014#include "aos/events/logging/eigen_mpq.h"
Austin Schuhcb5601b2020-09-10 15:29:59 -070015#include "aos/events/logging/log_namer.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070016#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080017#include "aos/events/logging/logfile_utils.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080018#include "aos/events/logging/logger_generated.h"
Austin Schuh64fab802020-09-09 22:47:47 -070019#include "aos/events/logging/uuid.h"
Austin Schuh92547522019-12-28 14:33:43 -080020#include "aos/events/simulated_event_loop.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070021#include "aos/network/message_bridge_server_generated.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080022#include "aos/network/remote_message_generated.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080023#include "aos/network/timestamp_filter.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "aos/time/time.h"
25#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070026#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027
28namespace aos {
29namespace logger {
30
Austin Schuhe309d2a2019-11-29 13:25:21 -080031// Logs all channels available in the event loop to disk every 100 ms.
32// Start by logging one message per channel to capture any state and
33// configuration that is sent rately on a channel and would affect execution.
34class Logger {
35 public:
Austin Schuh0c297012020-09-16 18:41:59 -070036 // Constructs a logger.
Austin Schuh0c297012020-09-16 18:41:59 -070037 // event_loop: The event loop used to read the messages.
Austin Schuh0c297012020-09-16 18:41:59 -070038 // configuration: When provided, this is the configuration to log, and the
39 // configuration to use for the channel list to log. If not provided,
40 // this becomes the configuration from the event loop.
Brian Silverman1f345222020-09-24 21:14:48 -070041 // should_log: When provided, a filter for channels to log. If not provided,
42 // all available channels are logged.
43 Logger(EventLoop *event_loop)
44 : Logger(event_loop, event_loop->configuration()) {}
45 Logger(EventLoop *event_loop, const Configuration *configuration)
46 : Logger(event_loop, configuration,
47 [](const Channel *) { return true; }) {}
48 Logger(EventLoop *event_loop, const Configuration *configuration,
49 std::function<bool(const Channel *)> should_log);
Austin Schuh0c297012020-09-16 18:41:59 -070050 ~Logger();
51
52 // Overrides the name in the log file header.
53 void set_name(std::string_view name) { name_ = name; }
Austin Schuhe309d2a2019-11-29 13:25:21 -080054
Brian Silverman1f345222020-09-24 21:14:48 -070055 // Sets the callback to run after each period of data is logged. Defaults to
56 // doing nothing.
57 //
58 // This callback may safely do things like call Rotate().
59 void set_on_logged_period(std::function<void()> on_logged_period) {
60 on_logged_period_ = std::move(on_logged_period);
61 }
62
63 // Sets the period between polling the data. Defaults to 100ms.
64 //
65 // Changing this while a set of files is being written may result in
66 // unreadable files.
67 void set_polling_period(std::chrono::nanoseconds polling_period) {
68 polling_period_ = polling_period;
69 }
70
Brian Silvermanae7c0332020-09-30 16:58:23 -070071 std::string_view log_start_uuid() const { return log_start_uuid_; }
Brian Silverman035e4182020-10-06 17:13:00 -070072 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
Brian Silvermanae7c0332020-09-30 16:58:23 -070073
Brian Silvermancb805822020-10-06 17:43:35 -070074 // The maximum time for a single fetch which returned a message, or 0 if none
75 // of those have happened.
76 std::chrono::nanoseconds max_message_fetch_time() const {
77 return max_message_fetch_time_;
78 }
79 // The channel for that longest fetch which returned a message, or -1 if none
80 // of those have happened.
81 int max_message_fetch_time_channel() const {
82 return max_message_fetch_time_channel_;
83 }
84 // The size of the message returned by that longest fetch, or -1 if none of
85 // those have happened.
86 int max_message_fetch_time_size() const {
87 return max_message_fetch_time_size_;
88 }
89 // The total time spent fetching messages.
90 std::chrono::nanoseconds total_message_fetch_time() const {
91 return total_message_fetch_time_;
92 }
93 // The total number of fetch calls which returned messages.
94 int total_message_fetch_count() const { return total_message_fetch_count_; }
95 // The total number of bytes fetched.
96 int64_t total_message_fetch_bytes() const {
97 return total_message_fetch_bytes_;
98 }
99
100 // The total time spent in fetches which did not return a message.
101 std::chrono::nanoseconds total_nop_fetch_time() const {
102 return total_nop_fetch_time_;
103 }
104 // The total number of fetches which did not return a message.
105 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
106
107 // The maximum time for a single copy, or 0 if none of those have happened.
108 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
109 // The channel for that longest copy, or -1 if none of those have happened.
110 int max_copy_time_channel() const { return max_copy_time_channel_; }
111 // The size of the message for that longest copy, or -1 if none of those have
112 // happened.
113 int max_copy_time_size() const { return max_copy_time_size_; }
114 // The total time spent copying messages.
115 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
116 // The total number of messages copied.
117 int total_copy_count() const { return total_copy_count_; }
118 // The total number of bytes copied.
119 int64_t total_copy_bytes() const { return total_copy_bytes_; }
120
121 void ResetStatisics();
122
Austin Schuh2f8fd752020-09-01 22:38:28 -0700123 // Rotates the log file(s), triggering new part files to be written for each
124 // log file.
125 void Rotate();
Austin Schuhfa895892020-01-07 20:07:41 -0800126
Brian Silverman1f345222020-09-24 21:14:48 -0700127 // Starts logging to files with the given naming scheme.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700128 //
129 // log_start_uuid may be used to tie this log event to other log events across
130 // multiple nodes. The default (empty string) indicates there isn't one
131 // available.
132 void StartLogging(std::unique_ptr<LogNamer> log_namer,
133 std::string_view log_start_uuid = "");
Brian Silverman1f345222020-09-24 21:14:48 -0700134
135 // Stops logging. Ensures any messages through end_time make it into the log.
136 //
137 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
138 //
139 // Returns the LogNamer in case the caller wants to do anything else with it
140 // before destroying it.
141 std::unique_ptr<LogNamer> StopLogging(
142 aos::monotonic_clock::time_point end_time);
143
144 // Returns whether a log is currently being written.
145 bool is_started() const { return static_cast<bool>(log_namer_); }
146
147 // Shortcut to call StartLogging with a LocalLogNamer when event processing
148 // starts.
149 void StartLoggingLocalNamerOnRun(std::string base_name) {
150 event_loop_->OnRun([this, base_name]() {
151 StartLogging(
152 std::make_unique<LocalLogNamer>(base_name, event_loop_->node()));
153 });
154 }
155
Austin Schuhe309d2a2019-11-29 13:25:21 -0800156 private:
Austin Schuhe309d2a2019-11-29 13:25:21 -0800157 // Structure to track both a fetcher, and if the data fetched has been
158 // written. We may want to delay writing data to disk so that we don't let
159 // data get too far out of order when written to disk so we can avoid making
160 // it too hard to sort when reading.
161 struct FetcherStruct {
162 std::unique_ptr<RawFetcher> fetcher;
163 bool written = false;
Austin Schuh15649d62019-12-28 16:36:38 -0800164
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700165 // Channel index to log to.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800166 int channel_index = -1;
Brian Silverman1f345222020-09-24 21:14:48 -0700167 const Channel *channel = nullptr;
168 const Node *timestamp_node = nullptr;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800169
170 LogType log_type = LogType::kLogMessage;
171
Brian Silverman1f345222020-09-24 21:14:48 -0700172 // We fill out the metadata at construction, but the actual writers have to
173 // be updated each time we start logging. To avoid duplicating the complex
174 // logic determining whether each writer should be initialized, we just
175 // stash the answer in separate member variables.
176 bool wants_writer = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800177 DetachedBufferWriter *writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700178 bool wants_timestamp_writer = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800179 DetachedBufferWriter *timestamp_writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700180 bool wants_contents_writer = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700181 DetachedBufferWriter *contents_writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700182
Austin Schuh315b96b2020-12-11 21:21:12 -0800183 // Node which this data is from, or -1 if it is unknown.
184 int data_node_index = -1;
185 // Node that this timestamp is for, or -1 if it is known.
186 int timestamp_node_index = -1;
187 // Node that the contents this contents_writer will log are from.
188 int contents_node_index = -1;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800189 };
190
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700191 // Vector mapping from the channel index from the event loop to the logged
192 // channel index.
193 std::vector<int> event_loop_to_logged_channel_index_;
194
Austin Schuh2f8fd752020-09-01 22:38:28 -0700195 struct NodeState {
196 aos::monotonic_clock::time_point monotonic_start_time =
197 aos::monotonic_clock::min_time;
198 aos::realtime_clock::time_point realtime_start_time =
199 aos::realtime_clock::min_time;
200
Austin Schuh315b96b2020-12-11 21:21:12 -0800201 bool has_source_node_boot_uuid = false;
202
203 // This is an initial UUID that is a valid UUID4 and is pretty obvious that
204 // it isn't valid.
205 std::string source_node_boot_uuid = "00000000-0000-4000-8000-000000000000";
206
Austin Schuh2f8fd752020-09-01 22:38:28 -0700207 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
208 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
Austin Schuh315b96b2020-12-11 21:21:12 -0800209
210 // True if a header has been written to the start of a log file.
211 bool header_written = false;
212 // True if the current written header represents the contents which will
213 // follow. This is cleared when boot_uuid is known to not match anymore.
214 bool header_valid = false;
215
216 // Sets the source_node_boot_uuid, properly updating everything.
217 void SetBootUUID(std::string_view new_source_node_boot_uuid) {
218 source_node_boot_uuid = new_source_node_boot_uuid;
219 header_valid = false;
220 has_source_node_boot_uuid = true;
221
222 flatbuffers::String *source_node_boot_uuid_string =
223 log_file_header.mutable_message()->mutable_source_node_boot_uuid();
224 CHECK_EQ(source_node_boot_uuid.size(),
225 source_node_boot_uuid_string->size());
226 memcpy(source_node_boot_uuid_string->data(), source_node_boot_uuid.data(),
227 source_node_boot_uuid.size());
228 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700229 };
Brian Silverman1f345222020-09-24 21:14:48 -0700230
231 void WriteHeader();
Austin Schuh315b96b2020-12-11 21:21:12 -0800232
Brian Silverman1f345222020-09-24 21:14:48 -0700233 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
234 const Node *node);
235
Austin Schuh315b96b2020-12-11 21:21:12 -0800236 // Writes the header for the provided node if enough information is valid.
237 void MaybeWriteHeader(int node_index);
238 // Overload for when we already know node as well.
239 void MaybeWriteHeader(int node_index, const Node *node);
240
Brian Silverman1f345222020-09-24 21:14:48 -0700241 bool MaybeUpdateTimestamp(
242 const Node *node, int node_index,
243 aos::monotonic_clock::time_point monotonic_start_time,
244 aos::realtime_clock::time_point realtime_start_time);
245
246 void DoLogData(const monotonic_clock::time_point end_time);
247
248 void WriteMissingTimestamps();
249
250 // Fetches from each channel until all the data is logged.
251 void LogUntil(monotonic_clock::time_point t);
252
Brian Silvermancb805822020-10-06 17:43:35 -0700253 void RecordFetchResult(aos::monotonic_clock::time_point start,
254 aos::monotonic_clock::time_point end, bool got_new,
255 FetcherStruct *fetcher);
256
257 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
258 aos::monotonic_clock::time_point end,
259 FetcherStruct *fetcher);
260
Brian Silverman1f345222020-09-24 21:14:48 -0700261 // Sets the start time for a specific node.
Austin Schuh315b96b2020-12-11 21:21:12 -0800262 void SetStartTime(
263 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
264 aos::realtime_clock::time_point realtime_start_time,
265 aos::monotonic_clock::time_point logger_monotonic_start_time,
266 aos::realtime_clock::time_point logger_realtime_start_time);
Brian Silverman1f345222020-09-24 21:14:48 -0700267
Brian Silvermanae7c0332020-09-30 16:58:23 -0700268 EventLoop *const event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700269 // The configuration to place at the top of the log file.
270 const Configuration *const configuration_;
271
Brian Silvermanae7c0332020-09-30 16:58:23 -0700272 UUID log_event_uuid_ = UUID::Zero();
273 const UUID logger_instance_uuid_ = UUID::Random();
274 std::unique_ptr<LogNamer> log_namer_;
275 // Empty indicates there isn't one.
276 std::string log_start_uuid_;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700277
Brian Silverman1f345222020-09-24 21:14:48 -0700278 // Name to save in the log file. Defaults to hostname.
279 std::string name_;
280
281 std::function<void()> on_logged_period_ = []() {};
282
Brian Silvermancb805822020-10-06 17:43:35 -0700283 std::chrono::nanoseconds max_message_fetch_time_ =
284 std::chrono::nanoseconds::zero();
285 int max_message_fetch_time_channel_ = -1;
286 int max_message_fetch_time_size_ = -1;
287 std::chrono::nanoseconds total_message_fetch_time_ =
288 std::chrono::nanoseconds::zero();
289 int total_message_fetch_count_ = 0;
290 int64_t total_message_fetch_bytes_ = 0;
291
292 std::chrono::nanoseconds total_nop_fetch_time_ =
293 std::chrono::nanoseconds::zero();
294 int total_nop_fetch_count_ = 0;
295
296 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
297 int max_copy_time_channel_ = -1;
298 int max_copy_time_size_ = -1;
299 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
300 int total_copy_count_ = 0;
301 int64_t total_copy_bytes_ = 0;
302
Brian Silverman1f345222020-09-24 21:14:48 -0700303 std::vector<FetcherStruct> fetchers_;
304 TimerHandler *timer_handler_;
305
306 // Period to poll the channels.
307 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
308
309 // Last time that data was written for all channels to disk.
310 monotonic_clock::time_point last_synchronized_time_;
311
312 // Max size that the header has consumed. This much extra data will be
313 // reserved in the builder to avoid reallocating.
314 size_t max_header_size_ = 0;
315
316 // Fetcher for all the statistics from all the nodes.
317 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
318
Austin Schuh2f8fd752020-09-01 22:38:28 -0700319 std::vector<NodeState> node_state_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800320};
321
Austin Schuh11d43732020-09-21 17:28:30 -0700322std::vector<std::vector<std::string>> ToLogReaderVector(
323 const std::vector<LogFile> &log_files);
Austin Schuh5212cad2020-09-09 23:12:09 -0700324
Austin Schuh6f3babe2020-01-26 20:34:50 -0800325// We end up with one of the following 3 log file types.
326//
327// Single node logged as the source node.
328// -> Replayed just on the source node.
329//
330// Forwarding timestamps only logged from the perspective of the destination
331// node.
332// -> Matched with data on source node and logged.
333//
334// Forwarding timestamps with data logged as the destination node.
335// -> Replayed just as the destination
336// -> Replayed as the source (Much harder, ordering is not defined)
337//
338// Duplicate data logged. -> CHECK that it matches and explode otherwise.
339//
340// This can be boiled down to a set of constraints and tools.
341//
342// 1) Forwarding timestamps and data need to be logged separately.
343// 2) Any forwarded data logged on the destination node needs to be logged
344// separately such that it can be sorted.
345//
346// 1) Log reader needs to be able to sort a list of log files.
347// 2) Log reader needs to be able to merge sorted lists of log files.
348// 3) Log reader needs to be able to match timestamps with messages.
349//
350// We also need to be able to generate multiple views of a log file depending on
351// the target.
352
Austin Schuhe309d2a2019-11-29 13:25:21 -0800353// Replays all the channels in the logfile to the event loop.
354class LogReader {
355 public:
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800356 // If you want to supply a new configuration that will be used for replay
357 // (e.g., to change message rates, or to populate an updated schema), then
358 // pass it in here. It must provide all the channels that the original logged
359 // config did.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800360 //
Austin Schuh287d43d2020-12-04 20:19:33 -0800361 // The single file constructor calls SortParts internally.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800362 LogReader(std::string_view filename,
363 const Configuration *replay_configuration = nullptr);
Austin Schuh287d43d2020-12-04 20:19:33 -0800364 LogReader(std::vector<LogFile> log_files,
Austin Schuh11d43732020-09-21 17:28:30 -0700365 const Configuration *replay_configuration = nullptr);
James Kuszmaul7daef362019-12-31 18:28:17 -0800366 ~LogReader();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800367
Austin Schuh6331ef92020-01-07 18:28:09 -0800368 // Registers all the callbacks to send the log file data out on an event loop
369 // created in event_loop_factory. This also updates time to be at the start
370 // of the log file by running until the log file starts.
371 // Note: the configuration used in the factory should be configuration()
372 // below, but can be anything as long as the locations needed to send
373 // everything are available.
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800374 void Register(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuh6331ef92020-01-07 18:28:09 -0800375 // Creates an SimulatedEventLoopFactory accessible via event_loop_factory(),
376 // and then calls Register.
377 void Register();
378 // Registers callbacks for all the events after the log file starts. This is
379 // only useful when replaying live.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800380 void Register(EventLoop *event_loop);
Austin Schuh6331ef92020-01-07 18:28:09 -0800381
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800382 // Unregisters the senders. You only need to call this if you separately
383 // supplied an event loop or event loop factory and the lifetimes are such
384 // that they need to be explicitly destroyed before the LogReader destructor
385 // gets called.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800386 void Deregister();
387
Austin Schuh0c297012020-09-16 18:41:59 -0700388 // Returns the configuration being used for replay from the log file.
389 // Note that this may be different from the configuration actually used for
390 // handling events. You should generally only use this to create a
391 // SimulatedEventLoopFactory, and then get the configuration from there for
392 // everything else.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800393 const Configuration *logged_configuration() const;
Austin Schuh11d43732020-09-21 17:28:30 -0700394 // Returns the configuration being used for replay from the log file.
395 // Note that this may be different from the configuration actually used for
396 // handling events. You should generally only use this to create a
397 // SimulatedEventLoopFactory, and then get the configuration from there for
398 // everything else.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800399 // The pointer is invalidated whenever RemapLoggedChannel is called.
Austin Schuh15649d62019-12-28 16:36:38 -0800400 const Configuration *configuration() const;
401
Austin Schuh6f3babe2020-01-26 20:34:50 -0800402 // Returns the nodes that this log file was created on. This is a list of
403 // pointers to a node in the nodes() list inside configuration(). The
404 // pointers here are invalidated whenever RemapLoggedChannel is called.
405 std::vector<const Node *> Nodes() const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800406
407 // Returns the starting timestamp for the log file.
Austin Schuh11d43732020-09-21 17:28:30 -0700408 monotonic_clock::time_point monotonic_start_time(
409 const Node *node = nullptr) const;
410 realtime_clock::time_point realtime_start_time(
411 const Node *node = nullptr) const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800412
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800413 // Causes the logger to publish the provided channel on a different name so
414 // that replayed applications can publish on the proper channel name without
415 // interference. This operates on raw channel names, without any node or
416 // application specific mappings.
417 void RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800418 std::string_view add_prefix = "/original",
419 std::string_view new_type = "");
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800420 template <typename T>
421 void RemapLoggedChannel(std::string_view name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800422 std::string_view add_prefix = "/original",
423 std::string_view new_type = "") {
424 RemapLoggedChannel(name, T::GetFullyQualifiedName(), add_prefix, new_type);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800425 }
426
Austin Schuh01b4c352020-09-21 23:09:39 -0700427 // Remaps the provided channel, though this respects node mappings, and
428 // preserves them too. This makes it so if /aos -> /pi1/aos on one node,
429 // /original/aos -> /original/pi1/aos on the same node after renaming, just
Austin Schuh0de30f32020-12-06 12:44:28 -0800430 // like you would hope. If new_type is not empty, the new channel will use
431 // the provided type instead. This allows for renaming messages.
Austin Schuh01b4c352020-09-21 23:09:39 -0700432 //
433 // TODO(austin): If you have 2 nodes remapping something to the same channel,
434 // this doesn't handle that. No use cases exist yet for that, so it isn't
435 // being done yet.
436 void RemapLoggedChannel(std::string_view name, std::string_view type,
437 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800438 std::string_view add_prefix = "/original",
439 std::string_view new_type = "");
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700440 template <typename T>
Austin Schuh01b4c352020-09-21 23:09:39 -0700441 void RemapLoggedChannel(std::string_view name, const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800442 std::string_view add_prefix = "/original",
443 std::string_view new_type = "") {
444 RemapLoggedChannel(name, T::GetFullyQualifiedName(), node, add_prefix,
445 new_type);
Austin Schuh01b4c352020-09-21 23:09:39 -0700446 }
447
448 template <typename T>
449 bool HasChannel(std::string_view name, const Node *node = nullptr) {
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700450 return configuration::GetChannel(log_file_header()->configuration(), name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800451 T::GetFullyQualifiedName(), "", node,
452 true) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700453 }
454
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800455 SimulatedEventLoopFactory *event_loop_factory() {
456 return event_loop_factory_;
457 }
458
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700459 const LogFileHeader *log_file_header() const {
460 return &log_file_header_.message();
461 }
462
Austin Schuh0c297012020-09-16 18:41:59 -0700463 std::string_view name() const {
464 return log_file_header()->name()->string_view();
465 }
466
Austin Schuhe309d2a2019-11-29 13:25:21 -0800467 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468 const Channel *RemapChannel(const EventLoop *event_loop,
469 const Channel *channel);
470
Austin Schuhe309d2a2019-11-29 13:25:21 -0800471 // Queues at least max_out_of_order_duration_ messages into channels_.
472 void QueueMessages();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800473 // Handle constructing a configuration with all the additional remapped
474 // channels from calls to RemapLoggedChannel.
475 void MakeRemappedConfig();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800476
Austin Schuh2f8fd752020-09-01 22:38:28 -0700477 // Returns the number of nodes.
478 size_t nodes_count() const {
479 return !configuration::MultiNode(logged_configuration())
480 ? 1u
481 : logged_configuration()->nodes()->size();
482 }
483
Austin Schuh287d43d2020-12-04 20:19:33 -0800484 const std::vector<LogFile> log_files_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800485
486 // This is *a* log file header used to provide the logged config. The rest of
487 // the header is likely distracting.
Austin Schuhadd6eb32020-11-09 21:24:26 -0800488 SizePrefixedFlatbufferVector<LogFileHeader> log_file_header_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800489
Austin Schuh2f8fd752020-09-01 22:38:28 -0700490 // Returns [ta; tb; ...] = tuple[0] * t + tuple[1]
491 std::tuple<Eigen::Matrix<double, Eigen::Dynamic, 1>,
492 Eigen::Matrix<double, Eigen::Dynamic, 1>>
493 SolveOffsets();
494
495 void LogFit(std::string_view prefix);
Austin Schuh8bd96322020-02-13 21:18:22 -0800496
Austin Schuh6f3babe2020-01-26 20:34:50 -0800497 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700498 class State {
499 public:
Austin Schuh287d43d2020-12-04 20:19:33 -0800500 State(std::unique_ptr<TimestampMapper> timestamp_mapper);
501
502 // Connects up the timestamp mappers.
503 void AddPeer(State *peer);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800504
Austin Schuh858c9f32020-08-31 16:56:12 -0700505 // Returns the timestamps, channel_index, and message from a channel.
506 // update_time (will be) set to true when popping this message causes the
507 // filter to change the time offset estimation function.
Austin Schuh287d43d2020-12-04 20:19:33 -0800508 TimestampedMessage PopOldest(bool *update_time);
Austin Schuh858c9f32020-08-31 16:56:12 -0700509
510 // Returns the monotonic time of the oldest message.
511 monotonic_clock::time_point OldestMessageTime() const;
512
513 // Primes the queues inside State. Should be called before calling
514 // OldestMessageTime.
515 void SeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800516
Austin Schuh858c9f32020-08-31 16:56:12 -0700517 // Returns the starting time for this node.
518 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800519 return timestamp_mapper_ ? timestamp_mapper_->monotonic_start_time()
520 : monotonic_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700521 }
522 realtime_clock::time_point realtime_start_time() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800523 return timestamp_mapper_ ? timestamp_mapper_->realtime_start_time()
524 : realtime_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700525 }
526
527 // Sets the node event loop factory for replaying into a
528 // SimulatedEventLoopFactory. Returns the EventLoop to use.
529 EventLoop *SetNodeEventLoopFactory(
530 NodeEventLoopFactory *node_event_loop_factory);
531
532 // Sets and gets the event loop to use.
533 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
534 EventLoop *event_loop() { return event_loop_; }
535
Austin Schuh858c9f32020-08-31 16:56:12 -0700536 // Sets the current realtime offset from the monotonic clock for this node
537 // (if we are on a simulated event loop).
538 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
539 realtime_clock::time_point realtime_time) {
540 if (node_event_loop_factory_ != nullptr) {
541 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
542 realtime_time);
543 }
544 }
545
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700546 // Returns the MessageHeader sender to log delivery timestamps to for the
547 // provided remote node.
Austin Schuh0de30f32020-12-06 12:44:28 -0800548 aos::Sender<message_bridge::RemoteMessage> *RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700549 const Node *delivered_node);
550
Austin Schuh858c9f32020-08-31 16:56:12 -0700551 // Converts a timestamp from the monotonic clock on this node to the
552 // distributed clock.
553 distributed_clock::time_point ToDistributedClock(
554 monotonic_clock::time_point time) {
555 return node_event_loop_factory_->ToDistributedClock(time);
556 }
557
Austin Schuh2f8fd752020-09-01 22:38:28 -0700558 monotonic_clock::time_point FromDistributedClock(
559 distributed_clock::time_point time) {
560 return node_event_loop_factory_->FromDistributedClock(time);
561 }
562
Austin Schuh858c9f32020-08-31 16:56:12 -0700563 // Sets the offset (and slope) from the distributed clock.
564 void SetDistributedOffset(std::chrono::nanoseconds distributed_offset,
565 double distributed_slope) {
566 node_event_loop_factory_->SetDistributedOffset(distributed_offset,
567 distributed_slope);
568 }
569
570 // Returns the current time on the remote node which sends messages on
571 // channel_index.
572 monotonic_clock::time_point monotonic_remote_now(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700573 return channel_source_state_[channel_index]
574 ->node_event_loop_factory_->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700575 }
576
Austin Schuh2f8fd752020-09-01 22:38:28 -0700577 distributed_clock::time_point RemoteToDistributedClock(
578 size_t channel_index, monotonic_clock::time_point time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700579 return channel_source_state_[channel_index]
580 ->node_event_loop_factory_->ToDistributedClock(time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700581 }
582
583 const Node *remote_node(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700584 return channel_source_state_[channel_index]
585 ->node_event_loop_factory_->node();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700586 }
587
588 monotonic_clock::time_point monotonic_now() {
589 return node_event_loop_factory_->monotonic_now();
590 }
591
Austin Schuh858c9f32020-08-31 16:56:12 -0700592 // Sets the number of channels.
593 void SetChannelCount(size_t count);
594
595 // Sets the sender, filter, and target factory for a channel.
Austin Schuh0de30f32020-12-06 12:44:28 -0800596 void SetChannel(
597 size_t logged_channel_index, size_t factory_channel_index,
598 std::unique_ptr<RawSender> sender,
599 message_bridge::NoncausalOffsetEstimator *filter,
600 aos::Sender<message_bridge::RemoteMessage> *remote_timestamp_sender,
601 State *source_state);
Austin Schuh858c9f32020-08-31 16:56:12 -0700602
603 // Returns if we have read all the messages from all the logs.
Austin Schuh287d43d2020-12-04 20:19:33 -0800604 bool at_end() const {
605 return timestamp_mapper_ ? timestamp_mapper_->Front() == nullptr : true;
606 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700607
608 // Unregisters everything so we can destory the event loop.
609 void Deregister();
610
611 // Sets the current TimerHandle for the replay callback.
612 void set_timer_handler(TimerHandler *timer_handler) {
613 timer_handler_ = timer_handler;
614 }
615
616 // Sets the next wakeup time on the replay callback.
617 void Setup(monotonic_clock::time_point next_time) {
618 timer_handler_->Setup(next_time);
619 }
620
621 // Sends a buffer on the provided channel index.
Austin Schuh287d43d2020-12-04 20:19:33 -0800622 bool Send(const TimestampedMessage &timestamped_message);
Austin Schuh858c9f32020-08-31 16:56:12 -0700623
624 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700625 std::string DebugString() const {
626 std::stringstream messages;
627 size_t i = 0;
628 for (const auto &message : sorted_messages_) {
629 if (i < 7 || i + 7 > sorted_messages_.size()) {
630 messages << "sorted_messages[" << i
631 << "]: " << std::get<0>(message).monotonic_event_time << " "
632 << configuration::StrippedChannelToString(
633 event_loop_->configuration()->channels()->Get(
Austin Schuh287d43d2020-12-04 20:19:33 -0800634 std::get<0>(message).channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700635 << "\n";
636 } else if (i == 7) {
637 messages << "...\n";
638 }
639 ++i;
640 }
Austin Schuh287d43d2020-12-04 20:19:33 -0800641 if (!timestamp_mapper_) {
642 return messages.str();
643 }
644 return messages.str() + timestamp_mapper_->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700645 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700646
647 private:
648 // Log file.
Austin Schuh287d43d2020-12-04 20:19:33 -0800649 std::unique_ptr<TimestampMapper> timestamp_mapper_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700650
Austin Schuh287d43d2020-12-04 20:19:33 -0800651 std::deque<std::tuple<TimestampedMessage,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700652 message_bridge::NoncausalOffsetEstimator *>>
Austin Schuh858c9f32020-08-31 16:56:12 -0700653 sorted_messages_;
654
655 // Senders.
656 std::vector<std::unique_ptr<RawSender>> channels_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800657 std::vector<aos::Sender<message_bridge::RemoteMessage> *>
658 remote_timestamp_senders_;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700659 // The mapping from logged channel index to sent channel index. Needed for
660 // sending out MessageHeaders.
661 std::vector<int> factory_channel_index_;
662
663 struct SentTimestamp {
664 monotonic_clock::time_point monotonic_event_time =
665 monotonic_clock::min_time;
666 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
667 uint32_t queue_index = 0xffffffff;
668
669 // The queue index that this message *actually* was sent with.
670 uint32_t actual_queue_index = 0xffffffff;
671 };
672
673 // Stores all the timestamps that have been sent on this channel. This is
674 // only done for channels which are forwarded and on the node which
675 // initially sends the message.
676 //
677 // TODO(austin): This whole concept is a hack. We should be able to
678 // associate state with the message as it gets sorted and recover it.
679 std::vector<std::unique_ptr<std::vector<SentTimestamp>>> queue_index_map_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700680
681 // Factory (if we are in sim) that this loop was created on.
682 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
683 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
684 // Event loop.
685 EventLoop *event_loop_ = nullptr;
686 // And timer used to send messages.
687 TimerHandler *timer_handler_;
688
Austin Schuh8bd96322020-02-13 21:18:22 -0800689 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
690 // This corresponds to the object which is shared among all the channels
691 // going between 2 nodes. The second element in the tuple indicates if this
692 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700693 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800694
695 // List of NodeEventLoopFactorys (or nullptr if it isn't a forwarded
696 // channel) which correspond to the originating node.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700697 std::vector<State *> channel_source_state_;
698
Austin Schuh0de30f32020-12-06 12:44:28 -0800699 std::map<const Node *, aos::Sender<message_bridge::RemoteMessage>>
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700700 remote_timestamp_senders_map_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800701 };
702
Austin Schuh8bd96322020-02-13 21:18:22 -0800703 // Node index -> State.
704 std::vector<std::unique_ptr<State>> states_;
705
706 // Creates the requested filter if it doesn't exist, regardless of whether
707 // these nodes can actually communicate directly. The second return value
708 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700709 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
710 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800711
712 // FILE to write offsets to (if populated).
713 FILE *offset_fp_ = nullptr;
714 // Timestamp of the first piece of data used for the horizontal axis on the
715 // plot.
716 aos::realtime_clock::time_point first_time_;
717
718 // List of filters for a connection. The pointer to the first node will be
719 // less than the second node.
720 std::map<std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700721 std::tuple<message_bridge::NoncausalOffsetEstimator>>
Austin Schuh8bd96322020-02-13 21:18:22 -0800722 filters_;
723
724 // Returns the offset from the monotonic clock for a node to the distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700725 // clock. monotonic = distributed * slope() + offset();
726 double slope(int node_index) const {
727 CHECK_LT(node_index, time_slope_matrix_.rows())
James Kuszmaul46d82582020-05-09 19:50:09 -0700728 << ": Got too high of a node index.";
Austin Schuh2f8fd752020-09-01 22:38:28 -0700729 return time_slope_matrix_(node_index);
730 }
731 std::chrono::nanoseconds offset(int node_index) const {
732 CHECK_LT(node_index, time_offset_matrix_.rows())
733 << ": Got too high of a node index.";
734 return std::chrono::duration_cast<std::chrono::nanoseconds>(
735 std::chrono::duration<double>(time_offset_matrix_(node_index)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800736 }
737
738 // Updates the offset matrix solution and sets the per-node distributed
739 // offsets in the factory.
740 void UpdateOffsets();
741
Austin Schuh2f8fd752020-09-01 22:38:28 -0700742 // We have 2 types of equations to do a least squares regression over to fully
743 // constrain our time function.
744 //
745 // One is simple. The distributed clock is the average of all the clocks.
Brian Silverman87ac0402020-09-17 14:47:01 -0700746 // (ta + tb + tc + td) / num_nodes = t_distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700747 //
748 // The second is a bit more complicated. Our basic time conversion function
749 // is:
750 // tb = ta + (ta * slope + offset)
751 // We can rewrite this as follows
752 // tb - (1 + slope) * ta = offset
753 //
754 // From here, we have enough equations to solve for t{a,b,c,...} We want to
755 // take as an input the offsets and slope, and solve for the per-node times as
756 // a function of the distributed clock.
757 //
758 // We need to massage our equations to make this work. If we solve for the
759 // per-node times at two set distributed clock times, we will be able to
760 // recreate the linear function (we know it is linear). We can do a similar
761 // thing by breaking our equation up into:
Brian Silverman87ac0402020-09-17 14:47:01 -0700762 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700763 // [1/3 1/3 1/3 ] [ta] [t_distributed]
764 // [ 1 -1-m1 0 ] [tb] = [oab]
765 // [ 1 0 -1-m2 ] [tc] [oac]
766 //
767 // This solves to:
768 //
769 // [ta] [ a00 a01 a02] [t_distributed]
770 // [tb] = [ a10 a11 a12] * [oab]
771 // [tc] [ a20 a21 a22] [oac]
772 //
773 // and can be split into:
774 //
775 // [ta] [ a00 ] [a01 a02]
776 // [tb] = [ a10 ] * t_distributed + [a11 a12] * [oab]
777 // [tc] [ a20 ] [a21 a22] [oac]
778 //
779 // (map_matrix_ + slope_matrix_) * [ta; tb; tc] = [offset_matrix_];
780 // offset_matrix_ will be in nanoseconds.
781 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> map_matrix_;
782 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> slope_matrix_;
783 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1> offset_matrix_;
784 // Matrix tracking which offsets are valid.
785 Eigen::Matrix<bool, Eigen::Dynamic, 1> valid_matrix_;
786 // Matrix tracking the last valid matrix we used to determine connected nodes.
787 Eigen::Matrix<bool, Eigen::Dynamic, 1> last_valid_matrix_;
788 size_t cached_valid_node_count_ = 0;
Austin Schuh8bd96322020-02-13 21:18:22 -0800789
Austin Schuh2f8fd752020-09-01 22:38:28 -0700790 // [ta; tb; tc] = time_slope_matrix_ * t + time_offset_matrix;
791 // t is in seconds.
792 Eigen::Matrix<double, Eigen::Dynamic, 1> time_slope_matrix_;
793 Eigen::Matrix<double, Eigen::Dynamic, 1> time_offset_matrix_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800794
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800795 std::unique_ptr<FlatbufferDetachedBuffer<Configuration>>
796 remapped_configuration_buffer_;
797
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800798 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
799 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800800
801 // Map of channel indices to new name. The channel index will be an index into
802 // logged_configuration(), and the string key will be the name of the channel
803 // to send on instead of the logged channel name.
Austin Schuh0de30f32020-12-06 12:44:28 -0800804 struct RemappedChannel {
805 std::string remapped_name;
806 std::string new_type;
807 };
808 std::map<size_t, RemappedChannel> remapped_channels_;
Austin Schuh01b4c352020-09-21 23:09:39 -0700809 std::vector<MapT> maps_;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800810
Austin Schuh6f3babe2020-01-26 20:34:50 -0800811 // Number of nodes which still have data to send. This is used to figure out
812 // when to exit.
813 size_t live_nodes_ = 0;
814
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800815 const Configuration *remapped_configuration_ = nullptr;
816 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800817
818 // If true, the replay timer will ignore any missing data. This is used
819 // during startup when we are bootstrapping everything and trying to get to
820 // the start of all the log files.
821 bool ignore_missing_data_ = false;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800822};
823
824} // namespace logger
825} // namespace aos
826
827#endif // AOS_EVENTS_LOGGER_H_