blob: 56b99e8bfce9bd9cee153a66bdd4b37b090e7b90 [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 Schuh0ca1fd32020-12-18 22:53:05 -080022#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080023#include "aos/network/remote_message_generated.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080024#include "aos/network/timestamp_filter.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080025#include "aos/time/time.h"
26#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070027#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028
29namespace aos {
30namespace logger {
31
Austin Schuhe309d2a2019-11-29 13:25:21 -080032// Logs all channels available in the event loop to disk every 100 ms.
33// Start by logging one message per channel to capture any state and
34// configuration that is sent rately on a channel and would affect execution.
35class Logger {
36 public:
Austin Schuh0c297012020-09-16 18:41:59 -070037 // Constructs a logger.
Austin Schuh0c297012020-09-16 18:41:59 -070038 // event_loop: The event loop used to read the messages.
Austin Schuh0c297012020-09-16 18:41:59 -070039 // configuration: When provided, this is the configuration to log, and the
40 // configuration to use for the channel list to log. If not provided,
41 // this becomes the configuration from the event loop.
Brian Silverman1f345222020-09-24 21:14:48 -070042 // should_log: When provided, a filter for channels to log. If not provided,
43 // all available channels are logged.
44 Logger(EventLoop *event_loop)
45 : Logger(event_loop, event_loop->configuration()) {}
46 Logger(EventLoop *event_loop, const Configuration *configuration)
47 : Logger(event_loop, configuration,
48 [](const Channel *) { return true; }) {}
49 Logger(EventLoop *event_loop, const Configuration *configuration,
50 std::function<bool(const Channel *)> should_log);
Austin Schuh0c297012020-09-16 18:41:59 -070051 ~Logger();
52
53 // Overrides the name in the log file header.
54 void set_name(std::string_view name) { name_ = name; }
Austin Schuhe309d2a2019-11-29 13:25:21 -080055
Brian Silverman1f345222020-09-24 21:14:48 -070056 // Sets the callback to run after each period of data is logged. Defaults to
57 // doing nothing.
58 //
59 // This callback may safely do things like call Rotate().
60 void set_on_logged_period(std::function<void()> on_logged_period) {
61 on_logged_period_ = std::move(on_logged_period);
62 }
63
64 // Sets the period between polling the data. Defaults to 100ms.
65 //
66 // Changing this while a set of files is being written may result in
67 // unreadable files.
68 void set_polling_period(std::chrono::nanoseconds polling_period) {
69 polling_period_ = polling_period;
70 }
71
Brian Silvermanae7c0332020-09-30 16:58:23 -070072 std::string_view log_start_uuid() const { return log_start_uuid_; }
Brian Silverman035e4182020-10-06 17:13:00 -070073 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
Brian Silvermanae7c0332020-09-30 16:58:23 -070074
Brian Silvermancb805822020-10-06 17:43:35 -070075 // The maximum time for a single fetch which returned a message, or 0 if none
76 // of those have happened.
77 std::chrono::nanoseconds max_message_fetch_time() const {
78 return max_message_fetch_time_;
79 }
80 // The channel for that longest fetch which returned a message, or -1 if none
81 // of those have happened.
82 int max_message_fetch_time_channel() const {
83 return max_message_fetch_time_channel_;
84 }
85 // The size of the message returned by that longest fetch, or -1 if none of
86 // those have happened.
87 int max_message_fetch_time_size() const {
88 return max_message_fetch_time_size_;
89 }
90 // The total time spent fetching messages.
91 std::chrono::nanoseconds total_message_fetch_time() const {
92 return total_message_fetch_time_;
93 }
94 // The total number of fetch calls which returned messages.
95 int total_message_fetch_count() const { return total_message_fetch_count_; }
96 // The total number of bytes fetched.
97 int64_t total_message_fetch_bytes() const {
98 return total_message_fetch_bytes_;
99 }
100
101 // The total time spent in fetches which did not return a message.
102 std::chrono::nanoseconds total_nop_fetch_time() const {
103 return total_nop_fetch_time_;
104 }
105 // The total number of fetches which did not return a message.
106 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
107
108 // The maximum time for a single copy, or 0 if none of those have happened.
109 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
110 // The channel for that longest copy, or -1 if none of those have happened.
111 int max_copy_time_channel() const { return max_copy_time_channel_; }
112 // The size of the message for that longest copy, or -1 if none of those have
113 // happened.
114 int max_copy_time_size() const { return max_copy_time_size_; }
115 // The total time spent copying messages.
116 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
117 // The total number of messages copied.
118 int total_copy_count() const { return total_copy_count_; }
119 // The total number of bytes copied.
120 int64_t total_copy_bytes() const { return total_copy_bytes_; }
121
122 void ResetStatisics();
123
Austin Schuh2f8fd752020-09-01 22:38:28 -0700124 // Rotates the log file(s), triggering new part files to be written for each
125 // log file.
126 void Rotate();
Austin Schuhfa895892020-01-07 20:07:41 -0800127
Brian Silverman1f345222020-09-24 21:14:48 -0700128 // Starts logging to files with the given naming scheme.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700129 //
130 // log_start_uuid may be used to tie this log event to other log events across
131 // multiple nodes. The default (empty string) indicates there isn't one
132 // available.
133 void StartLogging(std::unique_ptr<LogNamer> log_namer,
134 std::string_view log_start_uuid = "");
Brian Silverman1f345222020-09-24 21:14:48 -0700135
136 // Stops logging. Ensures any messages through end_time make it into the log.
137 //
138 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
139 //
140 // Returns the LogNamer in case the caller wants to do anything else with it
141 // before destroying it.
142 std::unique_ptr<LogNamer> StopLogging(
143 aos::monotonic_clock::time_point end_time);
144
145 // Returns whether a log is currently being written.
146 bool is_started() const { return static_cast<bool>(log_namer_); }
147
148 // Shortcut to call StartLogging with a LocalLogNamer when event processing
149 // starts.
150 void StartLoggingLocalNamerOnRun(std::string base_name) {
151 event_loop_->OnRun([this, base_name]() {
152 StartLogging(
153 std::make_unique<LocalLogNamer>(base_name, event_loop_->node()));
154 });
155 }
156
Austin Schuhe309d2a2019-11-29 13:25:21 -0800157 private:
Austin Schuhe309d2a2019-11-29 13:25:21 -0800158 // Structure to track both a fetcher, and if the data fetched has been
159 // written. We may want to delay writing data to disk so that we don't let
160 // data get too far out of order when written to disk so we can avoid making
161 // it too hard to sort when reading.
162 struct FetcherStruct {
163 std::unique_ptr<RawFetcher> fetcher;
164 bool written = false;
Austin Schuh15649d62019-12-28 16:36:38 -0800165
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700166 // Channel index to log to.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800167 int channel_index = -1;
Brian Silverman1f345222020-09-24 21:14:48 -0700168 const Channel *channel = nullptr;
169 const Node *timestamp_node = nullptr;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800170
171 LogType log_type = LogType::kLogMessage;
172
Brian Silverman1f345222020-09-24 21:14:48 -0700173 // We fill out the metadata at construction, but the actual writers have to
174 // be updated each time we start logging. To avoid duplicating the complex
175 // logic determining whether each writer should be initialized, we just
176 // stash the answer in separate member variables.
177 bool wants_writer = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800178 DetachedBufferWriter *writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700179 bool wants_timestamp_writer = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800180 DetachedBufferWriter *timestamp_writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700181 bool wants_contents_writer = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700182 DetachedBufferWriter *contents_writer = nullptr;
Brian Silverman1f345222020-09-24 21:14:48 -0700183
Austin Schuh315b96b2020-12-11 21:21:12 -0800184 // Node which this data is from, or -1 if it is unknown.
185 int data_node_index = -1;
186 // Node that this timestamp is for, or -1 if it is known.
187 int timestamp_node_index = -1;
188 // Node that the contents this contents_writer will log are from.
189 int contents_node_index = -1;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800190 };
191
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700192 // Vector mapping from the channel index from the event loop to the logged
193 // channel index.
194 std::vector<int> event_loop_to_logged_channel_index_;
195
Austin Schuh2f8fd752020-09-01 22:38:28 -0700196 struct NodeState {
197 aos::monotonic_clock::time_point monotonic_start_time =
198 aos::monotonic_clock::min_time;
199 aos::realtime_clock::time_point realtime_start_time =
200 aos::realtime_clock::min_time;
201
Austin Schuh315b96b2020-12-11 21:21:12 -0800202 bool has_source_node_boot_uuid = false;
203
204 // This is an initial UUID that is a valid UUID4 and is pretty obvious that
205 // it isn't valid.
206 std::string source_node_boot_uuid = "00000000-0000-4000-8000-000000000000";
207
Austin Schuh2f8fd752020-09-01 22:38:28 -0700208 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
209 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
Austin Schuh315b96b2020-12-11 21:21:12 -0800210
211 // True if a header has been written to the start of a log file.
212 bool header_written = false;
213 // True if the current written header represents the contents which will
214 // follow. This is cleared when boot_uuid is known to not match anymore.
215 bool header_valid = false;
216
217 // Sets the source_node_boot_uuid, properly updating everything.
218 void SetBootUUID(std::string_view new_source_node_boot_uuid) {
219 source_node_boot_uuid = new_source_node_boot_uuid;
220 header_valid = false;
221 has_source_node_boot_uuid = true;
222
223 flatbuffers::String *source_node_boot_uuid_string =
224 log_file_header.mutable_message()->mutable_source_node_boot_uuid();
225 CHECK_EQ(source_node_boot_uuid.size(),
226 source_node_boot_uuid_string->size());
227 memcpy(source_node_boot_uuid_string->data(), source_node_boot_uuid.data(),
228 source_node_boot_uuid.size());
229 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700230 };
Brian Silverman1f345222020-09-24 21:14:48 -0700231
232 void WriteHeader();
Austin Schuh315b96b2020-12-11 21:21:12 -0800233
Brian Silverman1f345222020-09-24 21:14:48 -0700234 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
235 const Node *node);
236
Austin Schuh315b96b2020-12-11 21:21:12 -0800237 // Writes the header for the provided node if enough information is valid.
238 void MaybeWriteHeader(int node_index);
239 // Overload for when we already know node as well.
240 void MaybeWriteHeader(int node_index, const Node *node);
241
Brian Silverman1f345222020-09-24 21:14:48 -0700242 bool MaybeUpdateTimestamp(
243 const Node *node, int node_index,
244 aos::monotonic_clock::time_point monotonic_start_time,
245 aos::realtime_clock::time_point realtime_start_time);
246
247 void DoLogData(const monotonic_clock::time_point end_time);
248
249 void WriteMissingTimestamps();
250
251 // Fetches from each channel until all the data is logged.
252 void LogUntil(monotonic_clock::time_point t);
253
Brian Silvermancb805822020-10-06 17:43:35 -0700254 void RecordFetchResult(aos::monotonic_clock::time_point start,
255 aos::monotonic_clock::time_point end, bool got_new,
256 FetcherStruct *fetcher);
257
258 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
259 aos::monotonic_clock::time_point end,
260 FetcherStruct *fetcher);
261
Brian Silverman1f345222020-09-24 21:14:48 -0700262 // Sets the start time for a specific node.
Austin Schuh315b96b2020-12-11 21:21:12 -0800263 void SetStartTime(
264 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
265 aos::realtime_clock::time_point realtime_start_time,
266 aos::monotonic_clock::time_point logger_monotonic_start_time,
267 aos::realtime_clock::time_point logger_realtime_start_time);
Brian Silverman1f345222020-09-24 21:14:48 -0700268
Brian Silvermanae7c0332020-09-30 16:58:23 -0700269 EventLoop *const event_loop_;
Brian Silverman1f345222020-09-24 21:14:48 -0700270 // The configuration to place at the top of the log file.
271 const Configuration *const configuration_;
272
Brian Silvermanae7c0332020-09-30 16:58:23 -0700273 UUID log_event_uuid_ = UUID::Zero();
274 const UUID logger_instance_uuid_ = UUID::Random();
275 std::unique_ptr<LogNamer> log_namer_;
276 // Empty indicates there isn't one.
277 std::string log_start_uuid_;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700278
Brian Silverman1f345222020-09-24 21:14:48 -0700279 // Name to save in the log file. Defaults to hostname.
280 std::string name_;
281
282 std::function<void()> on_logged_period_ = []() {};
283
Brian Silvermancb805822020-10-06 17:43:35 -0700284 std::chrono::nanoseconds max_message_fetch_time_ =
285 std::chrono::nanoseconds::zero();
286 int max_message_fetch_time_channel_ = -1;
287 int max_message_fetch_time_size_ = -1;
288 std::chrono::nanoseconds total_message_fetch_time_ =
289 std::chrono::nanoseconds::zero();
290 int total_message_fetch_count_ = 0;
291 int64_t total_message_fetch_bytes_ = 0;
292
293 std::chrono::nanoseconds total_nop_fetch_time_ =
294 std::chrono::nanoseconds::zero();
295 int total_nop_fetch_count_ = 0;
296
297 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
298 int max_copy_time_channel_ = -1;
299 int max_copy_time_size_ = -1;
300 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
301 int total_copy_count_ = 0;
302 int64_t total_copy_bytes_ = 0;
303
Brian Silverman1f345222020-09-24 21:14:48 -0700304 std::vector<FetcherStruct> fetchers_;
305 TimerHandler *timer_handler_;
306
307 // Period to poll the channels.
308 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
309
310 // Last time that data was written for all channels to disk.
311 monotonic_clock::time_point last_synchronized_time_;
312
313 // Max size that the header has consumed. This much extra data will be
314 // reserved in the builder to avoid reallocating.
315 size_t max_header_size_ = 0;
316
317 // Fetcher for all the statistics from all the nodes.
318 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
319
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 std::vector<NodeState> node_state_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800321};
322
Austin Schuh11d43732020-09-21 17:28:30 -0700323std::vector<std::vector<std::string>> ToLogReaderVector(
324 const std::vector<LogFile> &log_files);
Austin Schuh5212cad2020-09-09 23:12:09 -0700325
Austin Schuh6f3babe2020-01-26 20:34:50 -0800326// We end up with one of the following 3 log file types.
327//
328// Single node logged as the source node.
329// -> Replayed just on the source node.
330//
331// Forwarding timestamps only logged from the perspective of the destination
332// node.
333// -> Matched with data on source node and logged.
334//
335// Forwarding timestamps with data logged as the destination node.
336// -> Replayed just as the destination
337// -> Replayed as the source (Much harder, ordering is not defined)
338//
339// Duplicate data logged. -> CHECK that it matches and explode otherwise.
340//
341// This can be boiled down to a set of constraints and tools.
342//
343// 1) Forwarding timestamps and data need to be logged separately.
344// 2) Any forwarded data logged on the destination node needs to be logged
345// separately such that it can be sorted.
346//
347// 1) Log reader needs to be able to sort a list of log files.
348// 2) Log reader needs to be able to merge sorted lists of log files.
349// 3) Log reader needs to be able to match timestamps with messages.
350//
351// We also need to be able to generate multiple views of a log file depending on
352// the target.
353
Austin Schuhe309d2a2019-11-29 13:25:21 -0800354// Replays all the channels in the logfile to the event loop.
355class LogReader {
356 public:
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800357 // If you want to supply a new configuration that will be used for replay
358 // (e.g., to change message rates, or to populate an updated schema), then
359 // pass it in here. It must provide all the channels that the original logged
360 // config did.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800361 //
Austin Schuh287d43d2020-12-04 20:19:33 -0800362 // The single file constructor calls SortParts internally.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800363 LogReader(std::string_view filename,
364 const Configuration *replay_configuration = nullptr);
Austin Schuh287d43d2020-12-04 20:19:33 -0800365 LogReader(std::vector<LogFile> log_files,
Austin Schuh11d43732020-09-21 17:28:30 -0700366 const Configuration *replay_configuration = nullptr);
James Kuszmaul7daef362019-12-31 18:28:17 -0800367 ~LogReader();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800368
Austin Schuh6331ef92020-01-07 18:28:09 -0800369 // Registers all the callbacks to send the log file data out on an event loop
370 // created in event_loop_factory. This also updates time to be at the start
371 // of the log file by running until the log file starts.
372 // Note: the configuration used in the factory should be configuration()
373 // below, but can be anything as long as the locations needed to send
374 // everything are available.
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800375 void Register(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuh6331ef92020-01-07 18:28:09 -0800376 // Creates an SimulatedEventLoopFactory accessible via event_loop_factory(),
377 // and then calls Register.
378 void Register();
379 // Registers callbacks for all the events after the log file starts. This is
380 // only useful when replaying live.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800381 void Register(EventLoop *event_loop);
Austin Schuh6331ef92020-01-07 18:28:09 -0800382
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800383 // Unregisters the senders. You only need to call this if you separately
384 // supplied an event loop or event loop factory and the lifetimes are such
385 // that they need to be explicitly destroyed before the LogReader destructor
386 // gets called.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800387 void Deregister();
388
Austin Schuh0c297012020-09-16 18:41:59 -0700389 // Returns the configuration being used for replay from the log file.
390 // Note that this may be different from the configuration actually used for
391 // handling events. You should generally only use this to create a
392 // SimulatedEventLoopFactory, and then get the configuration from there for
393 // everything else.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800394 const Configuration *logged_configuration() const;
Austin Schuh11d43732020-09-21 17:28:30 -0700395 // Returns the configuration being used for replay from the log file.
396 // Note that this may be different from the configuration actually used for
397 // handling events. You should generally only use this to create a
398 // SimulatedEventLoopFactory, and then get the configuration from there for
399 // everything else.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800400 // The pointer is invalidated whenever RemapLoggedChannel is called.
Austin Schuh15649d62019-12-28 16:36:38 -0800401 const Configuration *configuration() const;
402
Austin Schuh6f3babe2020-01-26 20:34:50 -0800403 // Returns the nodes that this log file was created on. This is a list of
404 // pointers to a node in the nodes() list inside configuration(). The
405 // pointers here are invalidated whenever RemapLoggedChannel is called.
406 std::vector<const Node *> Nodes() const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800407
408 // Returns the starting timestamp for the log file.
Austin Schuh11d43732020-09-21 17:28:30 -0700409 monotonic_clock::time_point monotonic_start_time(
410 const Node *node = nullptr) const;
411 realtime_clock::time_point realtime_start_time(
412 const Node *node = nullptr) const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800413
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800414 // Causes the logger to publish the provided channel on a different name so
415 // that replayed applications can publish on the proper channel name without
416 // interference. This operates on raw channel names, without any node or
417 // application specific mappings.
418 void RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800419 std::string_view add_prefix = "/original",
420 std::string_view new_type = "");
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800421 template <typename T>
422 void RemapLoggedChannel(std::string_view name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800423 std::string_view add_prefix = "/original",
424 std::string_view new_type = "") {
425 RemapLoggedChannel(name, T::GetFullyQualifiedName(), add_prefix, new_type);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800426 }
427
Austin Schuh01b4c352020-09-21 23:09:39 -0700428 // Remaps the provided channel, though this respects node mappings, and
429 // preserves them too. This makes it so if /aos -> /pi1/aos on one node,
430 // /original/aos -> /original/pi1/aos on the same node after renaming, just
Austin Schuh0de30f32020-12-06 12:44:28 -0800431 // like you would hope. If new_type is not empty, the new channel will use
432 // the provided type instead. This allows for renaming messages.
Austin Schuh01b4c352020-09-21 23:09:39 -0700433 //
434 // TODO(austin): If you have 2 nodes remapping something to the same channel,
435 // this doesn't handle that. No use cases exist yet for that, so it isn't
436 // being done yet.
437 void RemapLoggedChannel(std::string_view name, std::string_view type,
438 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800439 std::string_view add_prefix = "/original",
440 std::string_view new_type = "");
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700441 template <typename T>
Austin Schuh01b4c352020-09-21 23:09:39 -0700442 void RemapLoggedChannel(std::string_view name, const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800443 std::string_view add_prefix = "/original",
444 std::string_view new_type = "") {
445 RemapLoggedChannel(name, T::GetFullyQualifiedName(), node, add_prefix,
446 new_type);
Austin Schuh01b4c352020-09-21 23:09:39 -0700447 }
448
449 template <typename T>
450 bool HasChannel(std::string_view name, const Node *node = nullptr) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800451 return configuration::GetChannel(logged_configuration(), name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800452 T::GetFullyQualifiedName(), "", node,
453 true) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700454 }
455
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800456 SimulatedEventLoopFactory *event_loop_factory() {
457 return event_loop_factory_;
458 }
459
Austin Schuh0ca51f32020-12-25 21:51:45 -0800460 std::string_view name() const { return log_files_[0].name; }
Austin Schuh0c297012020-09-16 18:41:59 -0700461
James Kuszmaul71a81932020-12-15 21:08:01 -0800462 // Set whether to exit the SimulatedEventLoopFactory when we finish reading
463 // the logfile.
464 void set_exit_on_finish(bool exit_on_finish) {
465 exit_on_finish_ = exit_on_finish;
466 }
467
Austin Schuhe309d2a2019-11-29 13:25:21 -0800468 private:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800469 const Channel *RemapChannel(const EventLoop *event_loop,
470 const Channel *channel);
471
Austin Schuhe309d2a2019-11-29 13:25:21 -0800472 // Queues at least max_out_of_order_duration_ messages into channels_.
473 void QueueMessages();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800474 // Handle constructing a configuration with all the additional remapped
475 // channels from calls to RemapLoggedChannel.
476 void MakeRemappedConfig();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800477
Austin Schuh2f8fd752020-09-01 22:38:28 -0700478 // Returns the number of nodes.
479 size_t nodes_count() const {
480 return !configuration::MultiNode(logged_configuration())
481 ? 1u
482 : logged_configuration()->nodes()->size();
483 }
484
Austin Schuh287d43d2020-12-04 20:19:33 -0800485 const std::vector<LogFile> log_files_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800486
Austin Schuh6f3babe2020-01-26 20:34:50 -0800487 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700488 class State {
489 public:
Austin Schuh287d43d2020-12-04 20:19:33 -0800490 State(std::unique_ptr<TimestampMapper> timestamp_mapper);
491
492 // Connects up the timestamp mappers.
493 void AddPeer(State *peer);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800494
Austin Schuh858c9f32020-08-31 16:56:12 -0700495 // Returns the timestamps, channel_index, and message from a channel.
496 // update_time (will be) set to true when popping this message causes the
497 // filter to change the time offset estimation function.
Austin Schuh287d43d2020-12-04 20:19:33 -0800498 TimestampedMessage PopOldest(bool *update_time);
Austin Schuh858c9f32020-08-31 16:56:12 -0700499
500 // Returns the monotonic time of the oldest message.
501 monotonic_clock::time_point OldestMessageTime() const;
502
503 // Primes the queues inside State. Should be called before calling
504 // OldestMessageTime.
505 void SeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800506
Austin Schuh858c9f32020-08-31 16:56:12 -0700507 // Returns the starting time for this node.
508 monotonic_clock::time_point monotonic_start_time() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800509 return timestamp_mapper_ ? timestamp_mapper_->monotonic_start_time()
510 : monotonic_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700511 }
512 realtime_clock::time_point realtime_start_time() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800513 return timestamp_mapper_ ? timestamp_mapper_->realtime_start_time()
514 : realtime_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700515 }
516
517 // Sets the node event loop factory for replaying into a
518 // SimulatedEventLoopFactory. Returns the EventLoop to use.
519 EventLoop *SetNodeEventLoopFactory(
520 NodeEventLoopFactory *node_event_loop_factory);
521
522 // Sets and gets the event loop to use.
523 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
524 EventLoop *event_loop() { return event_loop_; }
525
Austin Schuh858c9f32020-08-31 16:56:12 -0700526 // Sets the current realtime offset from the monotonic clock for this node
527 // (if we are on a simulated event loop).
528 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
529 realtime_clock::time_point realtime_time) {
530 if (node_event_loop_factory_ != nullptr) {
531 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
532 realtime_time);
533 }
534 }
535
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700536 // Returns the MessageHeader sender to log delivery timestamps to for the
537 // provided remote node.
Austin Schuh0de30f32020-12-06 12:44:28 -0800538 aos::Sender<message_bridge::RemoteMessage> *RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700539 const Node *delivered_node);
540
Austin Schuh858c9f32020-08-31 16:56:12 -0700541 // Converts a timestamp from the monotonic clock on this node to the
542 // distributed clock.
543 distributed_clock::time_point ToDistributedClock(
544 monotonic_clock::time_point time) {
545 return node_event_loop_factory_->ToDistributedClock(time);
546 }
547
Austin Schuh858c9f32020-08-31 16:56:12 -0700548 // Returns the current time on the remote node which sends messages on
549 // channel_index.
550 monotonic_clock::time_point monotonic_remote_now(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700551 return channel_source_state_[channel_index]
552 ->node_event_loop_factory_->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700553 }
554
Austin Schuh2f8fd752020-09-01 22:38:28 -0700555 distributed_clock::time_point RemoteToDistributedClock(
556 size_t channel_index, monotonic_clock::time_point time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700557 return channel_source_state_[channel_index]
558 ->node_event_loop_factory_->ToDistributedClock(time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700559 }
560
561 const Node *remote_node(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700562 return channel_source_state_[channel_index]
563 ->node_event_loop_factory_->node();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700564 }
565
566 monotonic_clock::time_point monotonic_now() {
567 return node_event_loop_factory_->monotonic_now();
568 }
569
Austin Schuh858c9f32020-08-31 16:56:12 -0700570 // Sets the number of channels.
571 void SetChannelCount(size_t count);
572
573 // Sets the sender, filter, and target factory for a channel.
Austin Schuh0de30f32020-12-06 12:44:28 -0800574 void SetChannel(
575 size_t logged_channel_index, size_t factory_channel_index,
576 std::unique_ptr<RawSender> sender,
577 message_bridge::NoncausalOffsetEstimator *filter,
578 aos::Sender<message_bridge::RemoteMessage> *remote_timestamp_sender,
579 State *source_state);
Austin Schuh858c9f32020-08-31 16:56:12 -0700580
581 // Returns if we have read all the messages from all the logs.
Austin Schuh287d43d2020-12-04 20:19:33 -0800582 bool at_end() const {
583 return timestamp_mapper_ ? timestamp_mapper_->Front() == nullptr : true;
584 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700585
586 // Unregisters everything so we can destory the event loop.
587 void Deregister();
588
589 // Sets the current TimerHandle for the replay callback.
590 void set_timer_handler(TimerHandler *timer_handler) {
591 timer_handler_ = timer_handler;
592 }
593
594 // Sets the next wakeup time on the replay callback.
595 void Setup(monotonic_clock::time_point next_time) {
596 timer_handler_->Setup(next_time);
597 }
598
599 // Sends a buffer on the provided channel index.
Austin Schuh287d43d2020-12-04 20:19:33 -0800600 bool Send(const TimestampedMessage &timestamped_message);
Austin Schuh858c9f32020-08-31 16:56:12 -0700601
602 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700603 std::string DebugString() const {
604 std::stringstream messages;
605 size_t i = 0;
606 for (const auto &message : sorted_messages_) {
607 if (i < 7 || i + 7 > sorted_messages_.size()) {
608 messages << "sorted_messages[" << i
609 << "]: " << std::get<0>(message).monotonic_event_time << " "
610 << configuration::StrippedChannelToString(
611 event_loop_->configuration()->channels()->Get(
Austin Schuh287d43d2020-12-04 20:19:33 -0800612 std::get<0>(message).channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700613 << "\n";
614 } else if (i == 7) {
615 messages << "...\n";
616 }
617 ++i;
618 }
Austin Schuh287d43d2020-12-04 20:19:33 -0800619 if (!timestamp_mapper_) {
620 return messages.str();
621 }
622 return messages.str() + timestamp_mapper_->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700623 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700624
625 private:
626 // Log file.
Austin Schuh287d43d2020-12-04 20:19:33 -0800627 std::unique_ptr<TimestampMapper> timestamp_mapper_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700628
Austin Schuh287d43d2020-12-04 20:19:33 -0800629 std::deque<std::tuple<TimestampedMessage,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700630 message_bridge::NoncausalOffsetEstimator *>>
Austin Schuh858c9f32020-08-31 16:56:12 -0700631 sorted_messages_;
632
633 // Senders.
634 std::vector<std::unique_ptr<RawSender>> channels_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800635 std::vector<aos::Sender<message_bridge::RemoteMessage> *>
636 remote_timestamp_senders_;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700637 // The mapping from logged channel index to sent channel index. Needed for
638 // sending out MessageHeaders.
639 std::vector<int> factory_channel_index_;
640
641 struct SentTimestamp {
642 monotonic_clock::time_point monotonic_event_time =
643 monotonic_clock::min_time;
644 realtime_clock::time_point realtime_event_time = realtime_clock::min_time;
645 uint32_t queue_index = 0xffffffff;
646
647 // The queue index that this message *actually* was sent with.
648 uint32_t actual_queue_index = 0xffffffff;
649 };
650
651 // Stores all the timestamps that have been sent on this channel. This is
652 // only done for channels which are forwarded and on the node which
653 // initially sends the message.
654 //
655 // TODO(austin): This whole concept is a hack. We should be able to
656 // associate state with the message as it gets sorted and recover it.
657 std::vector<std::unique_ptr<std::vector<SentTimestamp>>> queue_index_map_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700658
659 // Factory (if we are in sim) that this loop was created on.
660 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
661 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
662 // Event loop.
663 EventLoop *event_loop_ = nullptr;
664 // And timer used to send messages.
665 TimerHandler *timer_handler_;
666
Austin Schuh8bd96322020-02-13 21:18:22 -0800667 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
668 // This corresponds to the object which is shared among all the channels
669 // going between 2 nodes. The second element in the tuple indicates if this
670 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700671 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800672
673 // List of NodeEventLoopFactorys (or nullptr if it isn't a forwarded
674 // channel) which correspond to the originating node.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700675 std::vector<State *> channel_source_state_;
676
Austin Schuh0de30f32020-12-06 12:44:28 -0800677 std::map<const Node *, aos::Sender<message_bridge::RemoteMessage>>
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700678 remote_timestamp_senders_map_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800679 };
680
Austin Schuh8bd96322020-02-13 21:18:22 -0800681 // Node index -> State.
682 std::vector<std::unique_ptr<State>> states_;
683
684 // Creates the requested filter if it doesn't exist, regardless of whether
685 // these nodes can actually communicate directly. The second return value
686 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700687 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
688 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800689
Austin Schuh8bd96322020-02-13 21:18:22 -0800690 // List of filters for a connection. The pointer to the first node will be
691 // less than the second node.
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800692 std::unique_ptr<message_bridge::MultiNodeNoncausalOffsetEstimator> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800693
694 // Updates the offset matrix solution and sets the per-node distributed
695 // offsets in the factory.
696 void UpdateOffsets();
697
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800698 std::unique_ptr<FlatbufferDetachedBuffer<Configuration>>
699 remapped_configuration_buffer_;
700
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800701 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
702 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800703
704 // Map of channel indices to new name. The channel index will be an index into
705 // logged_configuration(), and the string key will be the name of the channel
706 // to send on instead of the logged channel name.
Austin Schuh0de30f32020-12-06 12:44:28 -0800707 struct RemappedChannel {
708 std::string remapped_name;
709 std::string new_type;
710 };
711 std::map<size_t, RemappedChannel> remapped_channels_;
Austin Schuh01b4c352020-09-21 23:09:39 -0700712 std::vector<MapT> maps_;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800713
Austin Schuh6f3babe2020-01-26 20:34:50 -0800714 // Number of nodes which still have data to send. This is used to figure out
715 // when to exit.
716 size_t live_nodes_ = 0;
717
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800718 const Configuration *remapped_configuration_ = nullptr;
719 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800720
721 // If true, the replay timer will ignore any missing data. This is used
722 // during startup when we are bootstrapping everything and trying to get to
723 // the start of all the log files.
724 bool ignore_missing_data_ = false;
James Kuszmaul71a81932020-12-15 21:08:01 -0800725
726 // Whether to exit the SimulatedEventLoop when we finish reading the logs.
727 bool exit_on_finish_ = true;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800728};
729
730} // namespace logger
731} // namespace aos
732
733#endif // AOS_EVENTS_LOGGER_H_