blob: ba764247f7db48cb06b10a9b7c2f3789455d43f1 [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
Austin Schuh01b4c352020-09-21 23:09:39 -0700261 // Remaps the provided channel, though this respects node mappings, and
262 // preserves them too. This makes it so if /aos -> /pi1/aos on one node,
263 // /original/aos -> /original/pi1/aos on the same node after renaming, just
264 // like you would hope.
265 //
266 // TODO(austin): If you have 2 nodes remapping something to the same channel,
267 // this doesn't handle that. No use cases exist yet for that, so it isn't
268 // being done yet.
269 void RemapLoggedChannel(std::string_view name, std::string_view type,
270 const Node *node,
271 std::string_view add_prefix = "/original");
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700272 template <typename T>
Austin Schuh01b4c352020-09-21 23:09:39 -0700273 void RemapLoggedChannel(std::string_view name, const Node *node,
274 std::string_view add_prefix = "/original") {
275 RemapLoggedChannel(name, T::GetFullyQualifiedName(), node, add_prefix);
276 }
277
278 template <typename T>
279 bool HasChannel(std::string_view name, const Node *node = nullptr) {
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700280 return configuration::GetChannel(log_file_header()->configuration(), name,
281 T::GetFullyQualifiedName(), "",
Austin Schuh01b4c352020-09-21 23:09:39 -0700282 node) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700283 }
284
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800285 SimulatedEventLoopFactory *event_loop_factory() {
286 return event_loop_factory_;
287 }
288
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700289 const LogFileHeader *log_file_header() const {
290 return &log_file_header_.message();
291 }
292
Austin Schuh0c297012020-09-16 18:41:59 -0700293 std::string_view name() const {
294 return log_file_header()->name()->string_view();
295 }
296
Austin Schuhe309d2a2019-11-29 13:25:21 -0800297 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800298 const Channel *RemapChannel(const EventLoop *event_loop,
299 const Channel *channel);
300
Austin Schuhe309d2a2019-11-29 13:25:21 -0800301 // Queues at least max_out_of_order_duration_ messages into channels_.
302 void QueueMessages();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800303 // Handle constructing a configuration with all the additional remapped
304 // channels from calls to RemapLoggedChannel.
305 void MakeRemappedConfig();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800306
Austin Schuh2f8fd752020-09-01 22:38:28 -0700307 // Returns the number of nodes.
308 size_t nodes_count() const {
309 return !configuration::MultiNode(logged_configuration())
310 ? 1u
311 : logged_configuration()->nodes()->size();
312 }
313
Austin Schuh6f3babe2020-01-26 20:34:50 -0800314 const std::vector<std::vector<std::string>> filenames_;
315
316 // This is *a* log file header used to provide the logged config. The rest of
317 // the header is likely distracting.
318 FlatbufferVector<LogFileHeader> log_file_header_;
319
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 // Returns [ta; tb; ...] = tuple[0] * t + tuple[1]
321 std::tuple<Eigen::Matrix<double, Eigen::Dynamic, 1>,
322 Eigen::Matrix<double, Eigen::Dynamic, 1>>
323 SolveOffsets();
324
325 void LogFit(std::string_view prefix);
Austin Schuh8bd96322020-02-13 21:18:22 -0800326
Austin Schuh6f3babe2020-01-26 20:34:50 -0800327 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700328 class State {
329 public:
330 State(std::unique_ptr<ChannelMerger> channel_merger);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800331
Austin Schuh858c9f32020-08-31 16:56:12 -0700332 // Returns the timestamps, channel_index, and message from a channel.
333 // update_time (will be) set to true when popping this message causes the
334 // filter to change the time offset estimation function.
335 std::tuple<TimestampMerger::DeliveryTimestamp, int,
336 FlatbufferVector<MessageHeader>>
337 PopOldest(bool *update_time);
338
339 // Returns the monotonic time of the oldest message.
340 monotonic_clock::time_point OldestMessageTime() const;
341
342 // Primes the queues inside State. Should be called before calling
343 // OldestMessageTime.
344 void SeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800345
Austin Schuh858c9f32020-08-31 16:56:12 -0700346 // Returns the starting time for this node.
347 monotonic_clock::time_point monotonic_start_time() const {
348 return channel_merger_->monotonic_start_time();
349 }
350 realtime_clock::time_point realtime_start_time() const {
351 return channel_merger_->realtime_start_time();
352 }
353
354 // Sets the node event loop factory for replaying into a
355 // SimulatedEventLoopFactory. Returns the EventLoop to use.
356 EventLoop *SetNodeEventLoopFactory(
357 NodeEventLoopFactory *node_event_loop_factory);
358
359 // Sets and gets the event loop to use.
360 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
361 EventLoop *event_loop() { return event_loop_; }
362
Austin Schuh858c9f32020-08-31 16:56:12 -0700363 // Sets the current realtime offset from the monotonic clock for this node
364 // (if we are on a simulated event loop).
365 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
366 realtime_clock::time_point realtime_time) {
367 if (node_event_loop_factory_ != nullptr) {
368 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
369 realtime_time);
370 }
371 }
372
373 // Converts a timestamp from the monotonic clock on this node to the
374 // distributed clock.
375 distributed_clock::time_point ToDistributedClock(
376 monotonic_clock::time_point time) {
377 return node_event_loop_factory_->ToDistributedClock(time);
378 }
379
Austin Schuh2f8fd752020-09-01 22:38:28 -0700380 monotonic_clock::time_point FromDistributedClock(
381 distributed_clock::time_point time) {
382 return node_event_loop_factory_->FromDistributedClock(time);
383 }
384
Austin Schuh858c9f32020-08-31 16:56:12 -0700385 // Sets the offset (and slope) from the distributed clock.
386 void SetDistributedOffset(std::chrono::nanoseconds distributed_offset,
387 double distributed_slope) {
388 node_event_loop_factory_->SetDistributedOffset(distributed_offset,
389 distributed_slope);
390 }
391
392 // Returns the current time on the remote node which sends messages on
393 // channel_index.
394 monotonic_clock::time_point monotonic_remote_now(size_t channel_index) {
395 return channel_target_event_loop_factory_[channel_index]->monotonic_now();
396 }
397
Austin Schuh2f8fd752020-09-01 22:38:28 -0700398 distributed_clock::time_point RemoteToDistributedClock(
399 size_t channel_index, monotonic_clock::time_point time) {
400 return channel_target_event_loop_factory_[channel_index]
401 ->ToDistributedClock(time);
402 }
403
404 const Node *remote_node(size_t channel_index) {
405 return channel_target_event_loop_factory_[channel_index]->node();
406 }
407
408 monotonic_clock::time_point monotonic_now() {
409 return node_event_loop_factory_->monotonic_now();
410 }
411
Austin Schuh858c9f32020-08-31 16:56:12 -0700412 // Sets the node we will be merging as, and returns true if there is any
413 // data on it.
414 bool SetNode() { return channel_merger_->SetNode(event_loop_->node()); }
415
416 // Sets the number of channels.
417 void SetChannelCount(size_t count);
418
419 // Sets the sender, filter, and target factory for a channel.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700420 void SetChannel(size_t channel, std::unique_ptr<RawSender> sender,
421 message_bridge::NoncausalOffsetEstimator *filter,
422 NodeEventLoopFactory *channel_target_event_loop_factory);
Austin Schuh858c9f32020-08-31 16:56:12 -0700423
424 // Returns if we have read all the messages from all the logs.
425 bool at_end() const { return channel_merger_->at_end(); }
426
427 // Unregisters everything so we can destory the event loop.
428 void Deregister();
429
430 // Sets the current TimerHandle for the replay callback.
431 void set_timer_handler(TimerHandler *timer_handler) {
432 timer_handler_ = timer_handler;
433 }
434
435 // Sets the next wakeup time on the replay callback.
436 void Setup(monotonic_clock::time_point next_time) {
437 timer_handler_->Setup(next_time);
438 }
439
440 // Sends a buffer on the provided channel index.
441 bool Send(size_t channel_index, const void *data, size_t size,
442 aos::monotonic_clock::time_point monotonic_remote_time,
443 aos::realtime_clock::time_point realtime_remote_time,
444 uint32_t remote_queue_index) {
445 return channels_[channel_index]->Send(data, size, monotonic_remote_time,
446 realtime_remote_time,
447 remote_queue_index);
448 }
449
450 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700451 std::string DebugString() const {
452 std::stringstream messages;
453 size_t i = 0;
454 for (const auto &message : sorted_messages_) {
455 if (i < 7 || i + 7 > sorted_messages_.size()) {
456 messages << "sorted_messages[" << i
457 << "]: " << std::get<0>(message).monotonic_event_time << " "
458 << configuration::StrippedChannelToString(
459 event_loop_->configuration()->channels()->Get(
460 std::get<2>(message).message().channel_index()))
461 << "\n";
462 } else if (i == 7) {
463 messages << "...\n";
464 }
465 ++i;
466 }
467 return messages.str() + channel_merger_->DebugString();
468 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700469
470 private:
471 // Log file.
472 std::unique_ptr<ChannelMerger> channel_merger_;
473
474 std::deque<std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700475 FlatbufferVector<MessageHeader>,
476 message_bridge::NoncausalOffsetEstimator *>>
Austin Schuh858c9f32020-08-31 16:56:12 -0700477 sorted_messages_;
478
479 // Senders.
480 std::vector<std::unique_ptr<RawSender>> channels_;
481
482 // Factory (if we are in sim) that this loop was created on.
483 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
484 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
485 // Event loop.
486 EventLoop *event_loop_ = nullptr;
487 // And timer used to send messages.
488 TimerHandler *timer_handler_;
489
Austin Schuh8bd96322020-02-13 21:18:22 -0800490 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
491 // This corresponds to the object which is shared among all the channels
492 // going between 2 nodes. The second element in the tuple indicates if this
493 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700494 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800495
496 // List of NodeEventLoopFactorys (or nullptr if it isn't a forwarded
497 // channel) which correspond to the originating node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700498 std::vector<NodeEventLoopFactory *> channel_target_event_loop_factory_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800499 };
500
Austin Schuh8bd96322020-02-13 21:18:22 -0800501 // Node index -> State.
502 std::vector<std::unique_ptr<State>> states_;
503
504 // Creates the requested filter if it doesn't exist, regardless of whether
505 // these nodes can actually communicate directly. The second return value
506 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700507 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
508 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800509
510 // FILE to write offsets to (if populated).
511 FILE *offset_fp_ = nullptr;
512 // Timestamp of the first piece of data used for the horizontal axis on the
513 // plot.
514 aos::realtime_clock::time_point first_time_;
515
516 // List of filters for a connection. The pointer to the first node will be
517 // less than the second node.
518 std::map<std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700519 std::tuple<message_bridge::NoncausalOffsetEstimator>>
Austin Schuh8bd96322020-02-13 21:18:22 -0800520 filters_;
521
522 // Returns the offset from the monotonic clock for a node to the distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700523 // clock. monotonic = distributed * slope() + offset();
524 double slope(int node_index) const {
525 CHECK_LT(node_index, time_slope_matrix_.rows())
James Kuszmaul46d82582020-05-09 19:50:09 -0700526 << ": Got too high of a node index.";
Austin Schuh2f8fd752020-09-01 22:38:28 -0700527 return time_slope_matrix_(node_index);
528 }
529 std::chrono::nanoseconds offset(int node_index) const {
530 CHECK_LT(node_index, time_offset_matrix_.rows())
531 << ": Got too high of a node index.";
532 return std::chrono::duration_cast<std::chrono::nanoseconds>(
533 std::chrono::duration<double>(time_offset_matrix_(node_index)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800534 }
535
536 // Updates the offset matrix solution and sets the per-node distributed
537 // offsets in the factory.
538 void UpdateOffsets();
539
Austin Schuh2f8fd752020-09-01 22:38:28 -0700540 // We have 2 types of equations to do a least squares regression over to fully
541 // constrain our time function.
542 //
543 // One is simple. The distributed clock is the average of all the clocks.
Brian Silverman87ac0402020-09-17 14:47:01 -0700544 // (ta + tb + tc + td) / num_nodes = t_distributed
Austin Schuh2f8fd752020-09-01 22:38:28 -0700545 //
546 // The second is a bit more complicated. Our basic time conversion function
547 // is:
548 // tb = ta + (ta * slope + offset)
549 // We can rewrite this as follows
550 // tb - (1 + slope) * ta = offset
551 //
552 // From here, we have enough equations to solve for t{a,b,c,...} We want to
553 // take as an input the offsets and slope, and solve for the per-node times as
554 // a function of the distributed clock.
555 //
556 // We need to massage our equations to make this work. If we solve for the
557 // per-node times at two set distributed clock times, we will be able to
558 // recreate the linear function (we know it is linear). We can do a similar
559 // thing by breaking our equation up into:
Brian Silverman87ac0402020-09-17 14:47:01 -0700560 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700561 // [1/3 1/3 1/3 ] [ta] [t_distributed]
562 // [ 1 -1-m1 0 ] [tb] = [oab]
563 // [ 1 0 -1-m2 ] [tc] [oac]
564 //
565 // This solves to:
566 //
567 // [ta] [ a00 a01 a02] [t_distributed]
568 // [tb] = [ a10 a11 a12] * [oab]
569 // [tc] [ a20 a21 a22] [oac]
570 //
571 // and can be split into:
572 //
573 // [ta] [ a00 ] [a01 a02]
574 // [tb] = [ a10 ] * t_distributed + [a11 a12] * [oab]
575 // [tc] [ a20 ] [a21 a22] [oac]
576 //
577 // (map_matrix_ + slope_matrix_) * [ta; tb; tc] = [offset_matrix_];
578 // offset_matrix_ will be in nanoseconds.
579 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> map_matrix_;
580 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic> slope_matrix_;
581 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1> offset_matrix_;
582 // Matrix tracking which offsets are valid.
583 Eigen::Matrix<bool, Eigen::Dynamic, 1> valid_matrix_;
584 // Matrix tracking the last valid matrix we used to determine connected nodes.
585 Eigen::Matrix<bool, Eigen::Dynamic, 1> last_valid_matrix_;
586 size_t cached_valid_node_count_ = 0;
Austin Schuh8bd96322020-02-13 21:18:22 -0800587
Austin Schuh2f8fd752020-09-01 22:38:28 -0700588 // [ta; tb; tc] = time_slope_matrix_ * t + time_offset_matrix;
589 // t is in seconds.
590 Eigen::Matrix<double, Eigen::Dynamic, 1> time_slope_matrix_;
591 Eigen::Matrix<double, Eigen::Dynamic, 1> time_offset_matrix_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800592
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800593 std::unique_ptr<FlatbufferDetachedBuffer<Configuration>>
594 remapped_configuration_buffer_;
595
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800596 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
597 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800598
599 // Map of channel indices to new name. The channel index will be an index into
600 // logged_configuration(), and the string key will be the name of the channel
601 // to send on instead of the logged channel name.
602 std::map<size_t, std::string> remapped_channels_;
Austin Schuh01b4c352020-09-21 23:09:39 -0700603 std::vector<MapT> maps_;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800604
Austin Schuh6f3babe2020-01-26 20:34:50 -0800605 // Number of nodes which still have data to send. This is used to figure out
606 // when to exit.
607 size_t live_nodes_ = 0;
608
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800609 const Configuration *remapped_configuration_ = nullptr;
610 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800611
612 // If true, the replay timer will ignore any missing data. This is used
613 // during startup when we are bootstrapping everything and trying to get to
614 // the start of all the log files.
615 bool ignore_missing_data_ = false;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800616};
617
618} // namespace logger
619} // namespace aos
620
621#endif // AOS_EVENTS_LOGGER_H_