blob: a3189dbe446211f7fa2218f74a29155e54c0549d [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 Schuha36c8902019-12-30 18:07:15 -080016#include "aos/events/logging/logfile_utils.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080017#include "aos/events/logging/logger_generated.h"
Austin Schuh64fab802020-09-09 22:47:47 -070018#include "aos/events/logging/uuid.h"
Austin Schuh92547522019-12-28 14:33:43 -080019#include "aos/events/simulated_event_loop.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070020#include "aos/network/message_bridge_server_generated.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080021#include "aos/network/timestamp_filter.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022#include "aos/time/time.h"
23#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070024#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080025
26namespace aos {
27namespace logger {
28
Austin Schuhe309d2a2019-11-29 13:25:21 -080029// Logs all channels available in the event loop to disk every 100 ms.
30// Start by logging one message per channel to capture any state and
31// configuration that is sent rately on a channel and would affect execution.
32class Logger {
33 public:
Austin Schuh0c297012020-09-16 18:41:59 -070034 // Constructs a logger.
35 // base_name/log_namer: Object used to write data to disk in one or more log
36 // files. If a base_name is passed in, a LocalLogNamer is wrapped
37 // around it.
38 // event_loop: The event loop used to read the messages.
39 // polling_period: The period used to poll the data.
40 // configuration: When provided, this is the configuration to log, and the
41 // configuration to use for the channel list to log. If not provided,
42 // this becomes the configuration from the event loop.
Austin Schuh2f8fd752020-09-01 22:38:28 -070043 Logger(std::string_view base_name, EventLoop *event_loop,
Austin Schuhe309d2a2019-11-29 13:25:21 -080044 std::chrono::milliseconds polling_period =
45 std::chrono::milliseconds(100));
Austin Schuh0c297012020-09-16 18:41:59 -070046 Logger(std::string_view base_name, EventLoop *event_loop,
47 const Configuration *configuration,
48 std::chrono::milliseconds polling_period =
49 std::chrono::milliseconds(100));
Austin Schuh6f3babe2020-01-26 20:34:50 -080050 Logger(std::unique_ptr<LogNamer> log_namer, EventLoop *event_loop,
51 std::chrono::milliseconds polling_period =
52 std::chrono::milliseconds(100));
Austin Schuh0c297012020-09-16 18:41:59 -070053 Logger(std::unique_ptr<LogNamer> log_namer, EventLoop *event_loop,
54 const Configuration *configuration,
55 std::chrono::milliseconds polling_period =
56 std::chrono::milliseconds(100));
57 ~Logger();
58
59 // Overrides the name in the log file header.
60 void set_name(std::string_view name) { name_ = name; }
Austin Schuhe309d2a2019-11-29 13:25:21 -080061
Austin Schuh2f8fd752020-09-01 22:38:28 -070062 // Rotates the log file(s), triggering new part files to be written for each
63 // log file.
64 void Rotate();
Austin Schuhfa895892020-01-07 20:07:41 -080065
Austin Schuhe309d2a2019-11-29 13:25:21 -080066 private:
Austin Schuhfa895892020-01-07 20:07:41 -080067 void WriteHeader();
Austin Schuh2f8fd752020-09-01 22:38:28 -070068 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
69 const Node *node);
70
71 bool MaybeUpdateTimestamp(
72 const Node *node, int node_index,
73 aos::monotonic_clock::time_point monotonic_start_time,
74 aos::realtime_clock::time_point realtime_start_time);
Austin Schuhfa895892020-01-07 20:07:41 -080075
Austin Schuhe309d2a2019-11-29 13:25:21 -080076 void DoLogData();
77
Austin Schuh2f8fd752020-09-01 22:38:28 -070078 void WriteMissingTimestamps();
79
80 void StartLogging();
81
82 // Fetches from each channel until all the data is logged.
83 void LogUntil(monotonic_clock::time_point t);
84
Austin Schuhe309d2a2019-11-29 13:25:21 -080085 EventLoop *event_loop_;
Austin Schuh64fab802020-09-09 22:47:47 -070086 const UUID uuid_;
Austin Schuh6f3babe2020-01-26 20:34:50 -080087 std::unique_ptr<LogNamer> log_namer_;
Austin Schuhe309d2a2019-11-29 13:25:21 -080088
Austin Schuh0c297012020-09-16 18:41:59 -070089 // The configuration to place at the top of the log file.
90 const Configuration *configuration_;
91
92 // Name to save in the log file. Defaults to hostname.
93 std::string name_;
94
Austin Schuhe309d2a2019-11-29 13:25:21 -080095 // Structure to track both a fetcher, and if the data fetched has been
96 // written. We may want to delay writing data to disk so that we don't let
97 // data get too far out of order when written to disk so we can avoid making
98 // it too hard to sort when reading.
99 struct FetcherStruct {
100 std::unique_ptr<RawFetcher> fetcher;
101 bool written = false;
Austin Schuh15649d62019-12-28 16:36:38 -0800102
Austin Schuh6f3babe2020-01-26 20:34:50 -0800103 int channel_index = -1;
104
105 LogType log_type = LogType::kLogMessage;
106
107 DetachedBufferWriter *writer = nullptr;
108 DetachedBufferWriter *timestamp_writer = nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700109 DetachedBufferWriter *contents_writer = nullptr;
110 const Node *writer_node = nullptr;
111 const Node *timestamp_node = nullptr;
112 int node_index = 0;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800113 };
114
115 std::vector<FetcherStruct> fetchers_;
116 TimerHandler *timer_handler_;
117
118 // Period to poll the channels.
119 const std::chrono::milliseconds polling_period_;
120
121 // Last time that data was written for all channels to disk.
122 monotonic_clock::time_point last_synchronized_time_;
123
Austin Schuhfa895892020-01-07 20:07:41 -0800124 monotonic_clock::time_point monotonic_start_time_;
125 realtime_clock::time_point realtime_start_time_;
126
Austin Schuhe309d2a2019-11-29 13:25:21 -0800127 // Max size that the header has consumed. This much extra data will be
128 // reserved in the builder to avoid reallocating.
129 size_t max_header_size_ = 0;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700130
131 // Fetcher for all the statistics from all the nodes.
132 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
133
134 // Sets the start time for a specific node.
135 void SetStartTime(size_t node_index,
136 aos::monotonic_clock::time_point monotonic_start_time,
137 aos::realtime_clock::time_point realtime_start_time);
138
139 struct NodeState {
140 aos::monotonic_clock::time_point monotonic_start_time =
141 aos::monotonic_clock::min_time;
142 aos::realtime_clock::time_point realtime_start_time =
143 aos::realtime_clock::min_time;
144
145 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
146 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
147 };
148 std::vector<NodeState> node_state_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800149};
150
Austin Schuh5212cad2020-09-09 23:12:09 -0700151// Takes a bunch of parts and sorts them based on part_uuid and part_index.
152std::vector<std::vector<std::string>> SortParts(
153 const std::vector<std::string> &parts);
154
Austin Schuh6f3babe2020-01-26 20:34:50 -0800155// We end up with one of the following 3 log file types.
156//
157// Single node logged as the source node.
158// -> Replayed just on the source node.
159//
160// Forwarding timestamps only logged from the perspective of the destination
161// node.
162// -> Matched with data on source node and logged.
163//
164// Forwarding timestamps with data logged as the destination node.
165// -> Replayed just as the destination
166// -> Replayed as the source (Much harder, ordering is not defined)
167//
168// Duplicate data logged. -> CHECK that it matches and explode otherwise.
169//
170// This can be boiled down to a set of constraints and tools.
171//
172// 1) Forwarding timestamps and data need to be logged separately.
173// 2) Any forwarded data logged on the destination node needs to be logged
174// separately such that it can be sorted.
175//
176// 1) Log reader needs to be able to sort a list of log files.
177// 2) Log reader needs to be able to merge sorted lists of log files.
178// 3) Log reader needs to be able to match timestamps with messages.
179//
180// We also need to be able to generate multiple views of a log file depending on
181// the target.
182
Austin Schuhe309d2a2019-11-29 13:25:21 -0800183// Replays all the channels in the logfile to the event loop.
184class LogReader {
185 public:
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800186 // If you want to supply a new configuration that will be used for replay
187 // (e.g., to change message rates, or to populate an updated schema), then
188 // pass it in here. It must provide all the channels that the original logged
189 // config did.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800190 //
191 // Log filenames are in the following format:
192 //
193 // {
194 // {log1_part0, log1_part1, ...},
195 // {log2}
196 // }
197 // The inner vector is a list of log file chunks which form up a log file.
198 // The outer vector is a list of log files with subsets of the messages, or
199 // messages from different nodes.
200 //
201 // If the outer vector isn't provided, it is assumed to be of size 1.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800202 LogReader(std::string_view filename,
203 const Configuration *replay_configuration = nullptr);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800204 LogReader(const std::vector<std::string> &filenames,
205 const Configuration *replay_configuration = nullptr);
206 LogReader(const std::vector<std::vector<std::string>> &filenames,
Austin Schuhfa895892020-01-07 20:07:41 -0800207 const Configuration *replay_configuration = nullptr);
James Kuszmaul7daef362019-12-31 18:28:17 -0800208 ~LogReader();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800209
Austin Schuh6331ef92020-01-07 18:28:09 -0800210 // Registers all the callbacks to send the log file data out on an event loop
211 // created in event_loop_factory. This also updates time to be at the start
212 // of the log file by running until the log file starts.
213 // Note: the configuration used in the factory should be configuration()
214 // below, but can be anything as long as the locations needed to send
215 // everything are available.
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800216 void Register(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuh6331ef92020-01-07 18:28:09 -0800217 // Creates an SimulatedEventLoopFactory accessible via event_loop_factory(),
218 // and then calls Register.
219 void Register();
220 // Registers callbacks for all the events after the log file starts. This is
221 // only useful when replaying live.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800222 void Register(EventLoop *event_loop);
Austin Schuh6331ef92020-01-07 18:28:09 -0800223
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800224 // Unregisters the senders. You only need to call this if you separately
225 // supplied an event loop or event loop factory and the lifetimes are such
226 // that they need to be explicitly destroyed before the LogReader destructor
227 // gets called.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800228 void Deregister();
229
Austin Schuh0c297012020-09-16 18:41:59 -0700230 // Returns the configuration being used for replay from the log file.
231 // Note that this may be different from the configuration actually used for
232 // handling events. You should generally only use this to create a
233 // SimulatedEventLoopFactory, and then get the configuration from there for
234 // everything else.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800235 const Configuration *logged_configuration() const;
236 // Returns the configuration being used for replay.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800237 // The pointer is invalidated whenever RemapLoggedChannel is called.
Austin Schuh15649d62019-12-28 16:36:38 -0800238 const Configuration *configuration() const;
239
Austin Schuh6f3babe2020-01-26 20:34:50 -0800240 // Returns the nodes that this log file was created on. This is a list of
241 // pointers to a node in the nodes() list inside configuration(). The
242 // pointers here are invalidated whenever RemapLoggedChannel is called.
243 std::vector<const Node *> Nodes() const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800244
245 // Returns the starting timestamp for the log file.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800246 monotonic_clock::time_point monotonic_start_time(const Node *node = nullptr);
247 realtime_clock::time_point realtime_start_time(const Node *node = nullptr);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800248
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800249 // Causes the logger to publish the provided channel on a different name so
250 // that replayed applications can publish on the proper channel name without
251 // interference. This operates on raw channel names, without any node or
252 // application specific mappings.
253 void RemapLoggedChannel(std::string_view name, std::string_view type,
254 std::string_view add_prefix = "/original");
255 template <typename T>
256 void RemapLoggedChannel(std::string_view name,
257 std::string_view add_prefix = "/original") {
258 RemapLoggedChannel(name, T::GetFullyQualifiedName(), add_prefix);
259 }
260
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700261 template <typename T>
262 bool HasChannel(std::string_view name) {
263 return configuration::GetChannel(log_file_header()->configuration(), name,
264 T::GetFullyQualifiedName(), "",
265 nullptr) != nullptr;
266 }
267
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800268 SimulatedEventLoopFactory *event_loop_factory() {
269 return event_loop_factory_;
270 }
271
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700272 const LogFileHeader *log_file_header() const {
273 return &log_file_header_.message();
274 }
275
Austin Schuh0c297012020-09-16 18:41:59 -0700276 std::string_view name() const {
277 return log_file_header()->name()->string_view();
278 }
279
Austin Schuhe309d2a2019-11-29 13:25:21 -0800280 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800281 const Channel *RemapChannel(const EventLoop *event_loop,
282 const Channel *channel);
283
Austin Schuhe309d2a2019-11-29 13:25:21 -0800284 // Queues at least max_out_of_order_duration_ messages into channels_.
285 void QueueMessages();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800286 // Handle constructing a configuration with all the additional remapped
287 // channels from calls to RemapLoggedChannel.
288 void MakeRemappedConfig();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800289
Austin Schuh2f8fd752020-09-01 22:38:28 -0700290 // Returns the number of nodes.
291 size_t nodes_count() const {
292 return !configuration::MultiNode(logged_configuration())
293 ? 1u
294 : logged_configuration()->nodes()->size();
295 }
296
Austin Schuh6f3babe2020-01-26 20:34:50 -0800297 const std::vector<std::vector<std::string>> filenames_;
298
299 // This is *a* log file header used to provide the logged config. The rest of
300 // the header is likely distracting.
301 FlatbufferVector<LogFileHeader> log_file_header_;
302
Austin Schuh2f8fd752020-09-01 22:38:28 -0700303 // Returns [ta; tb; ...] = tuple[0] * t + tuple[1]
304 std::tuple<Eigen::Matrix<double, Eigen::Dynamic, 1>,
305 Eigen::Matrix<double, Eigen::Dynamic, 1>>
306 SolveOffsets();
307
308 void LogFit(std::string_view prefix);
Austin Schuh8bd96322020-02-13 21:18:22 -0800309
Austin Schuh6f3babe2020-01-26 20:34:50 -0800310 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700311 class State {
312 public:
313 State(std::unique_ptr<ChannelMerger> channel_merger);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800314
Austin Schuh858c9f32020-08-31 16:56:12 -0700315 // Returns the timestamps, channel_index, and message from a channel.
316 // update_time (will be) set to true when popping this message causes the
317 // filter to change the time offset estimation function.
318 std::tuple<TimestampMerger::DeliveryTimestamp, int,
319 FlatbufferVector<MessageHeader>>
320 PopOldest(bool *update_time);
321
322 // Returns the monotonic time of the oldest message.
323 monotonic_clock::time_point OldestMessageTime() const;
324
325 // Primes the queues inside State. Should be called before calling
326 // OldestMessageTime.
327 void SeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800328
Austin Schuh858c9f32020-08-31 16:56:12 -0700329 // Returns the starting time for this node.
330 monotonic_clock::time_point monotonic_start_time() const {
331 return channel_merger_->monotonic_start_time();
332 }
333 realtime_clock::time_point realtime_start_time() const {
334 return channel_merger_->realtime_start_time();
335 }
336
337 // Sets the node event loop factory for replaying into a
338 // SimulatedEventLoopFactory. Returns the EventLoop to use.
339 EventLoop *SetNodeEventLoopFactory(
340 NodeEventLoopFactory *node_event_loop_factory);
341
342 // Sets and gets the event loop to use.
343 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
344 EventLoop *event_loop() { return event_loop_; }
345
Austin Schuh858c9f32020-08-31 16:56:12 -0700346 // Sets the current realtime offset from the monotonic clock for this node
347 // (if we are on a simulated event loop).
348 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
349 realtime_clock::time_point realtime_time) {
350 if (node_event_loop_factory_ != nullptr) {
351 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
352 realtime_time);
353 }
354 }
355
356 // Converts a timestamp from the monotonic clock on this node to the
357 // distributed clock.
358 distributed_clock::time_point ToDistributedClock(
359 monotonic_clock::time_point time) {
360 return node_event_loop_factory_->ToDistributedClock(time);
361 }
362
Austin Schuh2f8fd752020-09-01 22:38:28 -0700363 monotonic_clock::time_point FromDistributedClock(
364 distributed_clock::time_point time) {
365 return node_event_loop_factory_->FromDistributedClock(time);
366 }
367
Austin Schuh858c9f32020-08-31 16:56:12 -0700368 // Sets the offset (and slope) from the distributed clock.
369 void SetDistributedOffset(std::chrono::nanoseconds distributed_offset,
370 double distributed_slope) {
371 node_event_loop_factory_->SetDistributedOffset(distributed_offset,
372 distributed_slope);
373 }
374
375 // Returns the current time on the remote node which sends messages on
376 // channel_index.
377 monotonic_clock::time_point monotonic_remote_now(size_t channel_index) {
378 return channel_target_event_loop_factory_[channel_index]->monotonic_now();
379 }
380
Austin Schuh2f8fd752020-09-01 22:38:28 -0700381 distributed_clock::time_point RemoteToDistributedClock(
382 size_t channel_index, monotonic_clock::time_point time) {
383 return channel_target_event_loop_factory_[channel_index]
384 ->ToDistributedClock(time);
385 }
386
387 const Node *remote_node(size_t channel_index) {
388 return channel_target_event_loop_factory_[channel_index]->node();
389 }
390
391 monotonic_clock::time_point monotonic_now() {
392 return node_event_loop_factory_->monotonic_now();
393 }
394
Austin Schuh858c9f32020-08-31 16:56:12 -0700395 // Sets the node we will be merging as, and returns true if there is any
396 // data on it.
397 bool SetNode() { return channel_merger_->SetNode(event_loop_->node()); }
398
399 // Sets the number of channels.
400 void SetChannelCount(size_t count);
401
402 // Sets the sender, filter, and target factory for a channel.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700403 void SetChannel(size_t channel, std::unique_ptr<RawSender> sender,
404 message_bridge::NoncausalOffsetEstimator *filter,
405 NodeEventLoopFactory *channel_target_event_loop_factory);
Austin Schuh858c9f32020-08-31 16:56:12 -0700406
407 // Returns if we have read all the messages from all the logs.
408 bool at_end() const { return channel_merger_->at_end(); }
409
410 // Unregisters everything so we can destory the event loop.
411 void Deregister();
412
413 // Sets the current TimerHandle for the replay callback.
414 void set_timer_handler(TimerHandler *timer_handler) {
415 timer_handler_ = timer_handler;
416 }
417
418 // Sets the next wakeup time on the replay callback.
419 void Setup(monotonic_clock::time_point next_time) {
420 timer_handler_->Setup(next_time);
421 }
422
423 // Sends a buffer on the provided channel index.
424 bool Send(size_t channel_index, const void *data, size_t size,
425 aos::monotonic_clock::time_point monotonic_remote_time,
426 aos::realtime_clock::time_point realtime_remote_time,
427 uint32_t remote_queue_index) {
428 return channels_[channel_index]->Send(data, size, monotonic_remote_time,
429 realtime_remote_time,
430 remote_queue_index);
431 }
432
433 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700434 std::string DebugString() const {
435 std::stringstream messages;
436 size_t i = 0;
437 for (const auto &message : sorted_messages_) {
438 if (i < 7 || i + 7 > sorted_messages_.size()) {
439 messages << "sorted_messages[" << i
440 << "]: " << std::get<0>(message).monotonic_event_time << " "
441 << configuration::StrippedChannelToString(
442 event_loop_->configuration()->channels()->Get(
443 std::get<2>(message).message().channel_index()))
444 << "\n";
445 } else if (i == 7) {
446 messages << "...\n";
447 }
448 ++i;
449 }
450 return messages.str() + channel_merger_->DebugString();
451 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700452
453 private:
454 // Log file.
455 std::unique_ptr<ChannelMerger> channel_merger_;
456
457 std::deque<std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700458 FlatbufferVector<MessageHeader>,
459 message_bridge::NoncausalOffsetEstimator *>>
Austin Schuh858c9f32020-08-31 16:56:12 -0700460 sorted_messages_;
461
462 // Senders.
463 std::vector<std::unique_ptr<RawSender>> channels_;
464
465 // Factory (if we are in sim) that this loop was created on.
466 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
467 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
468 // Event loop.
469 EventLoop *event_loop_ = nullptr;
470 // And timer used to send messages.
471 TimerHandler *timer_handler_;
472
Austin Schuh8bd96322020-02-13 21:18:22 -0800473 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
474 // This corresponds to the object which is shared among all the channels
475 // going between 2 nodes. The second element in the tuple indicates if this
476 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700477 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800478
479 // List of NodeEventLoopFactorys (or nullptr if it isn't a forwarded
480 // channel) which correspond to the originating node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700481 std::vector<NodeEventLoopFactory *> channel_target_event_loop_factory_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800482 };
483
Austin Schuh8bd96322020-02-13 21:18:22 -0800484 // Node index -> State.
485 std::vector<std::unique_ptr<State>> states_;
486
487 // Creates the requested filter if it doesn't exist, regardless of whether
488 // these nodes can actually communicate directly. The second return value
489 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700490 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
491 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800492
493 // FILE to write offsets to (if populated).
494 FILE *offset_fp_ = nullptr;
495 // Timestamp of the first piece of data used for the horizontal axis on the
496 // plot.
497 aos::realtime_clock::time_point first_time_;
498
499 // List of filters for a connection. The pointer to the first node will be
500 // less than the second node.
501 std::map<std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700502 std::tuple<message_bridge::NoncausalOffsetEstimator>>
Austin Schuh8bd96322020-02-13 21:18:22 -0800503 filters_;
504
505 // Returns the offset from the monotonic clock for a node to the distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700506 // clock. monotonic = distributed * slope() + offset();
507 double slope(int node_index) const {
508 CHECK_LT(node_index, time_slope_matrix_.rows())
James Kuszmaul46d82582020-05-09 19:50:09 -0700509 << ": Got too high of a node index.";
Austin Schuh2f8fd752020-09-01 22:38:28 -0700510 return time_slope_matrix_(node_index);
511 }
512 std::chrono::nanoseconds offset(int node_index) const {
513 CHECK_LT(node_index, time_offset_matrix_.rows())
514 << ": Got too high of a node index.";
515 return std::chrono::duration_cast<std::chrono::nanoseconds>(
516 std::chrono::duration<double>(time_offset_matrix_(node_index)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800517 }
518
519 // Updates the offset matrix solution and sets the per-node distributed
520 // offsets in the factory.
521 void UpdateOffsets();
522
Austin Schuh2f8fd752020-09-01 22:38:28 -0700523 // We have 2 types of equations to do a least squares regression over to fully
524 // constrain our time function.
525 //
526 // One is simple. The distributed clock is the average of all the clocks.
Brian Silverman87ac0402020-09-17 14:47:01 -0700527 // (ta + tb + tc + td) / num_nodes = t_distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700528 //
529 // The second is a bit more complicated. Our basic time conversion function
530 // is:
531 // tb = ta + (ta * slope + offset)
532 // We can rewrite this as follows
533 // tb - (1 + slope) * ta = offset
534 //
535 // From here, we have enough equations to solve for t{a,b,c,...} We want to
536 // take as an input the offsets and slope, and solve for the per-node times as
537 // a function of the distributed clock.
538 //
539 // We need to massage our equations to make this work. If we solve for the
540 // per-node times at two set distributed clock times, we will be able to
541 // recreate the linear function (we know it is linear). We can do a similar
542 // thing by breaking our equation up into:
Brian Silverman87ac0402020-09-17 14:47:01 -0700543 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700544 // [1/3 1/3 1/3 ] [ta] [t_distributed]
545 // [ 1 -1-m1 0 ] [tb] = [oab]
546 // [ 1 0 -1-m2 ] [tc] [oac]
547 //
548 // This solves to:
549 //
550 // [ta] [ a00 a01 a02] [t_distributed]
551 // [tb] = [ a10 a11 a12] * [oab]
552 // [tc] [ a20 a21 a22] [oac]
553 //
554 // and can be split into:
555 //
556 // [ta] [ a00 ] [a01 a02]
557 // [tb] = [ a10 ] * t_distributed + [a11 a12] * [oab]
558 // [tc] [ a20 ] [a21 a22] [oac]
559 //
560 // (map_matrix_ + slope_matrix_) * [ta; tb; tc] = [offset_matrix_];
561 // offset_matrix_ will be in nanoseconds.
562 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> map_matrix_;
563 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> slope_matrix_;
564 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1> offset_matrix_;
565 // Matrix tracking which offsets are valid.
566 Eigen::Matrix<bool, Eigen::Dynamic, 1> valid_matrix_;
567 // Matrix tracking the last valid matrix we used to determine connected nodes.
568 Eigen::Matrix<bool, Eigen::Dynamic, 1> last_valid_matrix_;
569 size_t cached_valid_node_count_ = 0;
Austin Schuh8bd96322020-02-13 21:18:22 -0800570
Austin Schuh2f8fd752020-09-01 22:38:28 -0700571 // [ta; tb; tc] = time_slope_matrix_ * t + time_offset_matrix;
572 // t is in seconds.
573 Eigen::Matrix<double, Eigen::Dynamic, 1> time_slope_matrix_;
574 Eigen::Matrix<double, Eigen::Dynamic, 1> time_offset_matrix_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800575
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800576 std::unique_ptr<FlatbufferDetachedBuffer<Configuration>>
577 remapped_configuration_buffer_;
578
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800579 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
580 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800581
582 // Map of channel indices to new name. The channel index will be an index into
583 // logged_configuration(), and the string key will be the name of the channel
584 // to send on instead of the logged channel name.
585 std::map<size_t, std::string> remapped_channels_;
586
Austin Schuh6f3babe2020-01-26 20:34:50 -0800587 // Number of nodes which still have data to send. This is used to figure out
588 // when to exit.
589 size_t live_nodes_ = 0;
590
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800591 const Configuration *remapped_configuration_ = nullptr;
592 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800593
594 // If true, the replay timer will ignore any missing data. This is used
595 // during startup when we are bootstrapping everything and trying to get to
596 // the start of all the log files.
597 bool ignore_missing_data_ = false;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800598};
599
600} // namespace logger
601} // namespace aos
602
603#endif // AOS_EVENTS_LOGGER_H_