blob: fb19e784b1049e92bf9d95ed26ee8bf8e77b47f3 [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#ifndef AOS_EVENTS_LOGGING_LOG_READER_H_
2#define AOS_EVENTS_LOGGING_LOG_READER_H_
Austin Schuhe309d2a2019-11-29 13:25:21 -08003
Austin Schuh8bd96322020-02-13 21:18:22 -08004#include <chrono>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <deque>
James Kuszmaula16a7912022-06-17 10:58:12 -07006#include <queue>
James Kuszmaulc3f34d12022-08-15 15:57:55 -07007#include <string_view>
Austin Schuh2f8fd752020-09-01 22:38:28 -07008#include <tuple>
Austin Schuh6f3babe2020-01-26 20:34:50 -08009#include <vector>
Austin Schuhe309d2a2019-11-29 13:25:21 -080010
Philipp Schrader790cb542023-07-05 21:06:52 -070011#include "flatbuffers/flatbuffers.h"
Alexei Strots1f51ac72023-05-15 10:14:54 -070012#include "gflags/gflags.h"
13#include "glog/logging.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070014
James Kuszmaulc3f34d12022-08-15 15:57:55 -070015#include "aos/condition.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080016#include "aos/events/event_loop.h"
Eric Schmiedebergae00e732023-04-12 15:53:17 -060017#include "aos/events/event_loop_tmpl.h"
Eric Schmiedeberge279b532023-04-19 16:36:02 -060018#include "aos/events/logging/config_remapper.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070019#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080020#include "aos/events/logging/logfile_utils.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080021#include "aos/events/logging/logger_generated.h"
Eric Schmiedeberge279b532023-04-19 16:36:02 -060022#include "aos/events/logging/replay_channels.h"
James Kuszmaula16a7912022-06-17 10:58:12 -070023#include "aos/events/logging/replay_timing_generated.h"
James Kuszmaul09632422022-05-25 15:56:19 -070024#include "aos/events/shm_event_loop.h"
Austin Schuh92547522019-12-28 14:33:43 -080025#include "aos/events/simulated_event_loop.h"
James Kuszmaulc3f34d12022-08-15 15:57:55 -070026#include "aos/mutex/mutex.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070027#include "aos/network/message_bridge_server_generated.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080028#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080029#include "aos/network/remote_message_generated.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080030#include "aos/network/timestamp_filter.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080031#include "aos/time/time.h"
James Kuszmaula16a7912022-06-17 10:58:12 -070032#include "aos/util/threaded_queue.h"
James Kuszmaulc3f34d12022-08-15 15:57:55 -070033#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080034
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080035namespace aos::logger {
Austin Schuhe309d2a2019-11-29 13:25:21 -080036
Austin Schuhe33c08d2022-02-03 18:15:21 -080037class EventNotifier;
38
Austin Schuh6f3babe2020-01-26 20:34:50 -080039// We end up with one of the following 3 log file types.
40//
41// Single node logged as the source node.
42// -> Replayed just on the source node.
43//
44// Forwarding timestamps only logged from the perspective of the destination
45// node.
46// -> Matched with data on source node and logged.
47//
48// Forwarding timestamps with data logged as the destination node.
49// -> Replayed just as the destination
50// -> Replayed as the source (Much harder, ordering is not defined)
51//
52// Duplicate data logged. -> CHECK that it matches and explode otherwise.
53//
54// This can be boiled down to a set of constraints and tools.
55//
56// 1) Forwarding timestamps and data need to be logged separately.
57// 2) Any forwarded data logged on the destination node needs to be logged
58// separately such that it can be sorted.
59//
60// 1) Log reader needs to be able to sort a list of log files.
61// 2) Log reader needs to be able to merge sorted lists of log files.
62// 3) Log reader needs to be able to match timestamps with messages.
63//
64// We also need to be able to generate multiple views of a log file depending on
65// the target.
James Kuszmaul298b4a22023-06-28 20:01:03 -070066//
67// In general, we aim to guarantee that if you are using the LogReader
68// "normally" you should be able to observe all the messages that existed on the
69// live system between the start time and the end of the logfile, and that
70// CHECK-failures will be generated if the LogReader cannot satisfy that
71// guarantee. There are currently a few deliberate exceptions to this:
72// * Any channel marked NOT_LOGGED in the configuration is known not to
73// have been logged and thus will be silently absent in log replay.
74// * If an incomplete set of log files is provided to the reader (e.g.,
75// only logs logged on a single node on a multi-node system), then
76// any *individual* channel as observed on a given node will be
77// consistent, but similarly to a NOT_LOGGED channel, some data may
78// not be available.
79// * At the end of a log, data for some channels/nodes may end before
80// others; during this time period, you may observe silently dropped
81// messages. This will be most obvious on uncleanly terminated logs or
82// when merging logfiles across nodes (as the logs on different nodes
83// will not finish at identical times).
Austin Schuh6f3babe2020-01-26 20:34:50 -080084
Austin Schuhe309d2a2019-11-29 13:25:21 -080085// Replays all the channels in the logfile to the event loop.
86class LogReader {
87 public:
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -080088 // If you want to supply a new configuration that will be used for replay
89 // (e.g., to change message rates, or to populate an updated schema), then
90 // pass it in here. It must provide all the channels that the original logged
91 // config did.
Austin Schuh6f3babe2020-01-26 20:34:50 -080092 //
Eric Schmiedebergb38477e2022-12-02 16:08:04 -070093 // If certain messages should not be replayed, the replay_channels param can
94 // be used as an inclusive list of channels for messages to be replayed.
95 //
Austin Schuh287d43d2020-12-04 20:19:33 -080096 // The single file constructor calls SortParts internally.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -080097 LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -070098 const Configuration *replay_configuration = nullptr,
99 const ReplayChannels *replay_channels = nullptr);
Austin Schuh287d43d2020-12-04 20:19:33 -0800100 LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700101 const Configuration *replay_configuration = nullptr,
102 const ReplayChannels *replay_channels = nullptr);
Alexei Strots1f51ac72023-05-15 10:14:54 -0700103 LogReader(LogFilesContainer log_files,
104 const Configuration *replay_configuration = nullptr,
105 const ReplayChannels *replay_channels = nullptr);
James Kuszmaul7daef362019-12-31 18:28:17 -0800106 ~LogReader();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800107
Austin Schuh6331ef92020-01-07 18:28:09 -0800108 // Registers all the callbacks to send the log file data out on an event loop
109 // created in event_loop_factory. This also updates time to be at the start
110 // of the log file by running until the log file starts.
111 // Note: the configuration used in the factory should be configuration()
112 // below, but can be anything as long as the locations needed to send
113 // everything are available.
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800114 void Register(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800115
Austin Schuh58646e22021-08-23 23:51:46 -0700116 // Registers all the callbacks to send the log file data out to an event loop
117 // factory. This does not start replaying or change the current distributed
118 // time of the factory. It does change the monotonic clocks to be right.
119 void RegisterWithoutStarting(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800120 // Runs the log until the last start time. Register above is defined as:
121 // Register(...) {
122 // RegisterWithoutStarting
123 // StartAfterRegister
124 // }
125 // This should generally be considered as a stepping stone to convert from
126 // Register() to RegisterWithoutStarting() incrementally.
127 void StartAfterRegister(SimulatedEventLoopFactory *event_loop_factory);
128
Austin Schuh6331ef92020-01-07 18:28:09 -0800129 // Creates an SimulatedEventLoopFactory accessible via event_loop_factory(),
130 // and then calls Register.
131 void Register();
James Kuszmaul09632422022-05-25 15:56:19 -0700132
Austin Schuh6331ef92020-01-07 18:28:09 -0800133 // Registers callbacks for all the events after the log file starts. This is
134 // only useful when replaying live.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800135 void Register(EventLoop *event_loop);
Austin Schuh6331ef92020-01-07 18:28:09 -0800136
James Kuszmaula16a7912022-06-17 10:58:12 -0700137 // Sets a sender that should be used for tracking timing statistics. If not
138 // set, no statistics will be recorded.
139 void set_timing_accuracy_sender(
140 const Node *node, aos::Sender<timing::ReplayTiming> timing_sender) {
141 states_[configuration::GetNodeIndex(configuration(), node)]
142 ->set_timing_accuracy_sender(std::move(timing_sender));
143 }
144
Austin Schuh58646e22021-08-23 23:51:46 -0700145 // Called whenever a log file starts for a node.
James Kuszmaul82c3b512023-07-08 20:25:41 -0700146 // More precisely, this will be called on each boot at max of
147 // (realtime_start_time in the logfiles, SetStartTime()). If a given boot
148 // occurs entirely before the realtime_start_time, the OnStart handler will
149 // never get called for that boot.
150 //
151 // realtime_start_time is defined below, but/ essentially is the time at which
152 // message channels will start being internall consistent on a given node
153 // (i.e., when the logger started). Note: If you wish to see a watcher
154 // triggered for *every* message in a log, OnStart() will not be
155 // sufficient--messages (possibly multiple messages) may be present on
156 // channels prior to the start time. If attempting to do this, prefer to use
157 // NodeEventLoopFactory::OnStart.
Austin Schuh58646e22021-08-23 23:51:46 -0700158 void OnStart(std::function<void()> fn);
159 void OnStart(const Node *node, std::function<void()> fn);
James Kuszmaul82c3b512023-07-08 20:25:41 -0700160 // Called whenever a log file ends for a node on a given boot, or at the
161 // realtime_end_time specified by a flag or SetEndTime().
162 //
163 // A log file "ends" when there are no more messages to be replayed for that
164 // boot.
165 //
166 // If OnStart() is not called for a given boot, the OnEnd() handlers will not
167 // be called either. OnEnd() handlers will not be called if the logfile for a
168 // given boot has missing data that causes us to terminate replay early.
Austin Schuh58646e22021-08-23 23:51:46 -0700169 void OnEnd(std::function<void()> fn);
170 void OnEnd(const Node *node, std::function<void()> fn);
171
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800172 // Unregisters the senders. You only need to call this if you separately
173 // supplied an event loop or event loop factory and the lifetimes are such
174 // that they need to be explicitly destroyed before the LogReader destructor
175 // gets called.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800176 void Deregister();
177
Austin Schuh0c297012020-09-16 18:41:59 -0700178 // Returns the configuration being used for replay from the log file.
179 // Note that this may be different from the configuration actually used for
180 // handling events. You should generally only use this to create a
181 // SimulatedEventLoopFactory, and then get the configuration from there for
182 // everything else.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800183 const Configuration *logged_configuration() const;
Austin Schuh11d43732020-09-21 17:28:30 -0700184 // Returns the configuration being used for replay from the log file.
185 // Note that this may be different from the configuration actually used for
186 // handling events. You should generally only use this to create a
187 // SimulatedEventLoopFactory, and then get the configuration from there for
188 // everything else.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800189 // The pointer is invalidated whenever RemapLoggedChannel is called.
Austin Schuh15649d62019-12-28 16:36:38 -0800190 const Configuration *configuration() const;
191
Austin Schuh6f3babe2020-01-26 20:34:50 -0800192 // Returns the nodes that this log file was created on. This is a list of
Austin Schuh07676622021-01-21 18:59:17 -0800193 // pointers to a node in the nodes() list inside logged_configuration().
194 std::vector<const Node *> LoggedNodes() const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800195
196 // Returns the starting timestamp for the log file.
James Kuszmaul298b4a22023-06-28 20:01:03 -0700197 // All logged channels for the specified node should be entirely available
198 // after the specified time (i.e., any message that was available on the node
199 // in question after the monotonic start time but before the logs end and
200 // whose channel is present in any of the provided logs will either be
201 // available in the log or will result in an internal CHECK-failure of the
202 // LogReader if it would be skipped).
Austin Schuh11d43732020-09-21 17:28:30 -0700203 monotonic_clock::time_point monotonic_start_time(
204 const Node *node = nullptr) const;
205 realtime_clock::time_point realtime_start_time(
206 const Node *node = nullptr) const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800207
Austin Schuhe33c08d2022-02-03 18:15:21 -0800208 // Sets the start and end times to replay data until for all nodes. This
209 // overrides the --start_time and --end_time flags. The default is to replay
210 // all data.
211 void SetStartTime(std::string start_time);
212 void SetStartTime(realtime_clock::time_point start_time);
213 void SetEndTime(std::string end_time);
214 void SetEndTime(realtime_clock::time_point end_time);
215
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800216 // Causes the logger to publish the provided channel on a different name so
217 // that replayed applications can publish on the proper channel name without
218 // interference. This operates on raw channel names, without any node or
219 // application specific mappings.
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600220 void RemapLoggedChannel(std::string_view name, std::string_view type,
221 std::string_view add_prefix = "/original",
222 std::string_view new_type = "",
223 ConfigRemapper::RemapConflict conflict_handling =
224 ConfigRemapper::RemapConflict::kCascade);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800225 template <typename T>
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600226 void RemapLoggedChannel(std::string_view name,
227 std::string_view add_prefix = "/original",
228 std::string_view new_type = "",
229 ConfigRemapper::RemapConflict conflict_handling =
230 ConfigRemapper::RemapConflict::kCascade) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700231 RemapLoggedChannel(name, T::GetFullyQualifiedName(), add_prefix, new_type,
232 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800233 }
Austin Schuh01b4c352020-09-21 23:09:39 -0700234 // Remaps the provided channel, though this respects node mappings, and
235 // preserves them too. This makes it so if /aos -> /pi1/aos on one node,
236 // /original/aos -> /original/pi1/aos on the same node after renaming, just
Austin Schuh0de30f32020-12-06 12:44:28 -0800237 // like you would hope. If new_type is not empty, the new channel will use
238 // the provided type instead. This allows for renaming messages.
Austin Schuh01b4c352020-09-21 23:09:39 -0700239 //
240 // TODO(austin): If you have 2 nodes remapping something to the same channel,
241 // this doesn't handle that. No use cases exist yet for that, so it isn't
242 // being done yet.
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600243 void RemapLoggedChannel(std::string_view name, std::string_view type,
244 const Node *node,
245 std::string_view add_prefix = "/original",
246 std::string_view new_type = "",
247 ConfigRemapper::RemapConflict conflict_handling =
248 ConfigRemapper::RemapConflict::kCascade);
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700249 template <typename T>
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600250 void RemapLoggedChannel(std::string_view name, const Node *node,
251 std::string_view add_prefix = "/original",
252 std::string_view new_type = "",
253 ConfigRemapper::RemapConflict conflict_handling =
254 ConfigRemapper::RemapConflict::kCascade) {
Austin Schuh0de30f32020-12-06 12:44:28 -0800255 RemapLoggedChannel(name, T::GetFullyQualifiedName(), node, add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -0700256 new_type, conflict_handling);
Austin Schuh01b4c352020-09-21 23:09:39 -0700257 }
258
Sanjay Narayanan5ec00232022-07-08 15:21:30 -0700259 // Similar to RemapLoggedChannel(), but lets you specify a name for the new
260 // channel without constraints. This is useful when an application has been
261 // updated to use new channels but you want to support replaying old logs. By
262 // default, this will not add any maps for the new channel. Use add_maps to
263 // specify any maps you'd like added.
264 void RenameLoggedChannel(std::string_view name, std::string_view type,
265 std::string_view new_name,
266 const std::vector<MapT> &add_maps = {});
267 template <typename T>
268 void RenameLoggedChannel(std::string_view name, std::string_view new_name,
269 const std::vector<MapT> &add_maps = {}) {
270 RenameLoggedChannel(name, T::GetFullyQualifiedName(), new_name, add_maps);
271 }
272 // The following overloads are more suitable for multi-node configurations,
273 // and let you rename a channel on a specific node.
274 void RenameLoggedChannel(std::string_view name, std::string_view type,
275 const Node *node, std::string_view new_name,
276 const std::vector<MapT> &add_maps = {});
277 template <typename T>
278 void RenameLoggedChannel(std::string_view name, const Node *node,
279 std::string_view new_name,
280 const std::vector<MapT> &add_maps = {}) {
281 RenameLoggedChannel(name, T::GetFullyQualifiedName(), node, new_name,
282 add_maps);
283 }
284
Austin Schuh01b4c352020-09-21 23:09:39 -0700285 template <typename T>
286 bool HasChannel(std::string_view name, const Node *node = nullptr) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -0700287 return HasChannel(name, T::GetFullyQualifiedName(), node);
288 }
289 bool HasChannel(std::string_view name, std::string_view type,
290 const Node *node) {
291 return configuration::GetChannel(logged_configuration(), name, type, "",
292 node, true) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700293 }
294
Austin Schuh82529062021-12-08 12:09:52 -0800295 template <typename T>
296 void MaybeRemapLoggedChannel(std::string_view name,
297 const Node *node = nullptr) {
298 if (HasChannel<T>(name, node)) {
299 RemapLoggedChannel<T>(name, node);
300 }
301 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -0700302 template <typename T>
303 void MaybeRenameLoggedChannel(std::string_view name, const Node *node,
304 std::string_view new_name,
305 const std::vector<MapT> &add_maps = {}) {
306 if (HasChannel<T>(name, node)) {
307 RenameLoggedChannel<T>(name, node, new_name, add_maps);
308 }
309 }
Austin Schuh82529062021-12-08 12:09:52 -0800310
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800311 // Returns true if the channel exists on the node and was logged.
312 template <typename T>
313 bool HasLoggedChannel(std::string_view name, const Node *node = nullptr) {
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600314 return config_remapper_.HasOriginalChannel<T>(name, node);
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800315 }
316
Austin Schuh1c227352021-09-17 12:53:54 -0700317 // Returns a list of all the original channels from remapping.
318 std::vector<const Channel *> RemappedChannels() const;
319
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800320 SimulatedEventLoopFactory *event_loop_factory() {
321 return event_loop_factory_;
322 }
323
Alexei Strots1f51ac72023-05-15 10:14:54 -0700324 std::string_view name() const { return log_files_.name(); }
Austin Schuh0c297012020-09-16 18:41:59 -0700325
James Kuszmaul71a81932020-12-15 21:08:01 -0800326 // Set whether to exit the SimulatedEventLoopFactory when we finish reading
327 // the logfile.
328 void set_exit_on_finish(bool exit_on_finish) {
329 exit_on_finish_ = exit_on_finish;
330 }
James Kuszmaulb11a1502022-07-01 16:02:25 -0700331 bool exit_on_finish() const { return exit_on_finish_; }
James Kuszmaul71a81932020-12-15 21:08:01 -0800332
James Kuszmaulb67409b2022-06-20 16:25:03 -0700333 // Sets the realtime replay rate. A value of 1.0 will cause the scheduler to
334 // try to play events in realtime. 0.5 will run at half speed. Use infinity
335 // (the default) to run as fast as possible. This can be changed during
336 // run-time.
337 // Only applies when running against a SimulatedEventLoopFactory.
338 void SetRealtimeReplayRate(double replay_rate);
339
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600340 // Adds a callback for a channel to be called right before sending a message.
341 // This allows a user to mutate a message or do any processing when a specific
342 // type of message is sent on a channel. The name and type of the channel
343 // corresponds to the logged_configuration's name and type.
344 //
345 // Note, only one callback can be registered per channel in the current
346 // implementation. And, the callback is called only once one the Sender's Node
347 // if the channel is forwarded.
348 //
349 // See multinode_logger_test for examples of usage.
350 template <typename Callback>
351 void AddBeforeSendCallback(std::string_view channel_name,
352 Callback &&callback) {
353 CHECK(!AreStatesInitialized())
354 << ": Cannot add callbacks after calling Register";
355
356 using MessageType = typename std::remove_pointer<
357 typename event_loop_internal::watch_message_type_trait<
358 decltype(&Callback::operator())>::message_type>::type;
359
360 const Channel *channel = configuration::GetChannel(
361 logged_configuration(), channel_name,
362 MessageType::GetFullyQualifiedName(), "", nullptr);
363
364 CHECK(channel != nullptr)
365 << ": Channel { \"name\": \"" << channel_name << "\", \"type\": \""
366 << MessageType::GetFullyQualifiedName()
367 << "\" } not found in config for application.";
368 auto channel_index =
369 configuration::ChannelIndex(logged_configuration(), channel);
370
371 CHECK(!before_send_callbacks_[channel_index])
372 << ": Before Send Callback already registered for channel "
373 << ":{ \"name\": \"" << channel_name << "\", \"type\": \""
374 << MessageType::GetFullyQualifiedName() << "\" }";
375
376 before_send_callbacks_[channel_index] = [callback](void *message) {
377 callback(flatbuffers::GetMutableRoot<MessageType>(
378 reinterpret_cast<char *>(message)));
379 };
380 }
381
Austin Schuhe309d2a2019-11-29 13:25:21 -0800382 private:
Austin Schuh58646e22021-08-23 23:51:46 -0700383 void Register(EventLoop *event_loop, const Node *node);
384
385 void RegisterDuringStartup(EventLoop *event_loop, const Node *node);
386
387 const Channel *RemapChannel(const EventLoop *event_loop, const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800388 const Channel *channel);
389
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600390 // Checks if any states have their event loops initialized which indicates
391 // events have been scheduled
392 void CheckEventsAreNotScheduled();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800393
Austin Schuh2f8fd752020-09-01 22:38:28 -0700394 // Returns the number of nodes.
395 size_t nodes_count() const {
396 return !configuration::MultiNode(logged_configuration())
397 ? 1u
398 : logged_configuration()->nodes()->size();
399 }
400
James Kuszmaulb11a1502022-07-01 16:02:25 -0700401 // Handles when an individual node hits the realtime end time, exitting the
402 // entire event loop once all nodes are stopped.
403 void NoticeRealtimeEnd();
404
Alexei Strots1f51ac72023-05-15 10:14:54 -0700405 const LogFilesContainer log_files_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800406
Austin Schuh969cd602021-01-03 00:09:45 -0800407 // Class to manage sending RemoteMessages on the provided node after the
408 // correct delay.
Austin Schuh5ee56872021-01-30 16:53:34 -0800409 class RemoteMessageSender {
Austin Schuh969cd602021-01-03 00:09:45 -0800410 public:
411 RemoteMessageSender(aos::Sender<message_bridge::RemoteMessage> sender,
412 EventLoop *event_loop);
413 RemoteMessageSender(RemoteMessageSender const &) = delete;
414 RemoteMessageSender &operator=(RemoteMessageSender const &) = delete;
415
416 // Sends the provided message. If monotonic_timestamp_time is min_time,
417 // send it immediately.
418 void Send(
419 FlatbufferDetachedBuffer<message_bridge::RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -0700420 BootTimestamp monotonic_timestamp_time, size_t source_boot_count);
Austin Schuh969cd602021-01-03 00:09:45 -0800421
422 private:
423 // Handles actually sending the timestamp if we were delayed.
424 void SendTimestamp();
425 // Handles scheduling the timer to send at the correct time.
426 void ScheduleTimestamp();
427
428 EventLoop *event_loop_;
429 aos::Sender<message_bridge::RemoteMessage> sender_;
430 aos::TimerHandler *timer_;
431
432 // Time we are scheduled for, or min_time if we aren't scheduled.
433 monotonic_clock::time_point scheduled_time_ = monotonic_clock::min_time;
434
435 struct Timestamp {
436 Timestamp(FlatbufferDetachedBuffer<message_bridge::RemoteMessage>
437 new_remote_message,
438 monotonic_clock::time_point new_monotonic_timestamp_time)
439 : remote_message(std::move(new_remote_message)),
440 monotonic_timestamp_time(new_monotonic_timestamp_time) {}
441 FlatbufferDetachedBuffer<message_bridge::RemoteMessage> remote_message;
442 monotonic_clock::time_point monotonic_timestamp_time;
443 };
444
445 // List of messages to send. The timer works through them and then disables
446 // itself automatically.
447 std::deque<Timestamp> remote_timestamps_;
448 };
449
Austin Schuh6f3babe2020-01-26 20:34:50 -0800450 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700451 class State {
452 public:
James Kuszmaula16a7912022-06-17 10:58:12 -0700453 // Whether we should spin up a separate thread for buffering up messages.
454 // Only allowed in realtime replay--see comments on threading_ member for
455 // details.
456 enum class ThreadedBuffering { kYes, kNo };
James Kuszmaul09632422022-05-25 15:56:19 -0700457 State(std::unique_ptr<TimestampMapper> timestamp_mapper,
Austin Schuh63097262023-08-16 17:04:29 -0700458 TimestampQueueStrategy timestamp_queue_strategy,
James Kuszmaul09632422022-05-25 15:56:19 -0700459 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -0700460 std::function<void()> notice_realtime_end, const Node *node,
461 ThreadedBuffering threading,
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600462 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices,
463 const std::vector<std::function<void(void *message)>>
464 &before_send_callbacks);
Austin Schuh287d43d2020-12-04 20:19:33 -0800465
466 // Connects up the timestamp mappers.
467 void AddPeer(State *peer);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468
Austin Schuhe639ea12021-01-25 13:00:22 -0800469 TimestampMapper *timestamp_mapper() { return timestamp_mapper_.get(); }
470
Austin Schuhdda74ec2021-01-03 19:30:37 -0800471 // Returns the next sorted message with all the timestamps extracted and
472 // matched.
473 TimestampedMessage PopOldest();
Austin Schuh188eabe2020-12-29 23:41:13 -0800474
Austin Schuh858c9f32020-08-31 16:56:12 -0700475 // Returns the monotonic time of the oldest message.
James Kuszmaula16a7912022-06-17 10:58:12 -0700476 BootTimestamp SingleThreadedOldestMessageTime();
477 // Returns the monotonic time of the oldest message, handling querying the
478 // separate thread of ThreadedBuffering was set.
479 BootTimestamp MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -0700480
481 size_t boot_count() const {
482 // If we are replaying directly into an event loop, we can't reboot. So
483 // we will stay stuck on the 0th boot.
James Kuszmaul09632422022-05-25 15:56:19 -0700484 if (!node_event_loop_factory_) {
485 if (event_loop_ == nullptr) {
486 // If boot_count is being checked after startup for any of the
487 // non-primary nodes, then returning 0 may not be accurate (since
488 // remote nodes *can* reboot even if the EventLoop being played to
489 // can't).
490 CHECK(!started_);
491 CHECK(!stopped_);
492 }
493 return 0u;
494 }
Austin Schuh58646e22021-08-23 23:51:46 -0700495 return node_event_loop_factory_->boot_count();
496 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700497
Austin Schuh63097262023-08-16 17:04:29 -0700498 // Reads all the timestamps into RAM so we don't need to manage buffering
499 // them. For logs where the timestamps are in separate files, this
500 // minimizes RAM usage in the cases where the log reader decides to buffer
501 // to the end of the file, or where the time estimation buffer needs to be
502 // set high to sort. This means we devote our RAM to holding lots of
503 // timestamps instead of timestamps and much larger data for a shorter
504 // period. For logs where timestamps are stored with the data, this
505 // triggers those files to be read twice.
506 void ReadTimestamps();
507
Austin Schuh858c9f32020-08-31 16:56:12 -0700508 // Primes the queues inside State. Should be called before calling
509 // OldestMessageTime.
Austin Schuh63097262023-08-16 17:04:29 -0700510 void MaybeSeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800511
Philipp Schradera6712522023-07-05 20:25:11 -0700512 void SetUpStartupTimer() {
Austin Schuh58646e22021-08-23 23:51:46 -0700513 const monotonic_clock::time_point start_time =
514 monotonic_start_time(boot_count());
515 if (start_time == monotonic_clock::min_time) {
Austin Schuh3e31f912023-08-21 21:29:10 -0700516 if (event_loop_->node()) {
517 LOG(ERROR) << "No start time for "
518 << event_loop_->node()->name()->string_view()
519 << ", skipping.";
520 } else {
521 LOG(ERROR) << "No start time, skipping.";
522 }
523
524 // This is called from OnRun. There is too much complexity in supporting
525 // OnStartup callbacks from inside OnRun. Instead, schedule a timer for
526 // "now", and have that do what we need.
527 startup_timer_->Schedule(event_loop_->monotonic_now());
Austin Schuh58646e22021-08-23 23:51:46 -0700528 return;
529 }
James Kuszmaul09632422022-05-25 15:56:19 -0700530 if (node_event_loop_factory_) {
531 CHECK_GE(start_time + clock_offset(), event_loop_->monotonic_now());
532 }
Philipp Schradera6712522023-07-05 20:25:11 -0700533 startup_timer_->Schedule(start_time + clock_offset());
Austin Schuh58646e22021-08-23 23:51:46 -0700534 }
535
536 void set_startup_timer(TimerHandler *timer_handler) {
537 startup_timer_ = timer_handler;
538 if (startup_timer_) {
539 if (event_loop_->node() != nullptr) {
540 startup_timer_->set_name(absl::StrCat(
541 event_loop_->node()->name()->string_view(), "_startup"));
542 } else {
543 startup_timer_->set_name("startup");
544 }
545 }
546 }
547
Austin Schuh858c9f32020-08-31 16:56:12 -0700548 // Returns the starting time for this node.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700549 monotonic_clock::time_point monotonic_start_time(size_t boot_count) const {
550 return timestamp_mapper_
551 ? timestamp_mapper_->monotonic_start_time(boot_count)
552 : monotonic_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700553 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700554 realtime_clock::time_point realtime_start_time(size_t boot_count) const {
555 return timestamp_mapper_
556 ? timestamp_mapper_->realtime_start_time(boot_count)
557 : realtime_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700558 }
559
560 // Sets the node event loop factory for replaying into a
561 // SimulatedEventLoopFactory. Returns the EventLoop to use.
Austin Schuh60e77942022-05-16 17:48:24 -0700562 void SetNodeEventLoopFactory(NodeEventLoopFactory *node_event_loop_factory,
563 SimulatedEventLoopFactory *event_loop_factory);
Austin Schuh858c9f32020-08-31 16:56:12 -0700564
565 // Sets and gets the event loop to use.
566 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
567 EventLoop *event_loop() { return event_loop_; }
568
Austin Schuh58646e22021-08-23 23:51:46 -0700569 const Node *node() const { return node_; }
570
571 void Register(EventLoop *event_loop);
572
573 void OnStart(std::function<void()> fn);
574 void OnEnd(std::function<void()> fn);
575
Austin Schuh858c9f32020-08-31 16:56:12 -0700576 // Sets the current realtime offset from the monotonic clock for this node
577 // (if we are on a simulated event loop).
578 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
579 realtime_clock::time_point realtime_time) {
580 if (node_event_loop_factory_ != nullptr) {
581 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
582 realtime_time);
583 }
584 }
585
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700586 // Returns the MessageHeader sender to log delivery timestamps to for the
587 // provided remote node.
Austin Schuh61e973f2021-02-21 21:43:56 -0800588 RemoteMessageSender *RemoteTimestampSender(const Channel *channel,
589 const Connection *connection);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700590
Austin Schuh858c9f32020-08-31 16:56:12 -0700591 // Converts a timestamp from the monotonic clock on this node to the
592 // distributed clock.
593 distributed_clock::time_point ToDistributedClock(
594 monotonic_clock::time_point time) {
James Kuszmaul09632422022-05-25 15:56:19 -0700595 CHECK(node_event_loop_factory_);
Austin Schuh858c9f32020-08-31 16:56:12 -0700596 return node_event_loop_factory_->ToDistributedClock(time);
597 }
598
Austin Schuh858c9f32020-08-31 16:56:12 -0700599 // Returns the current time on the remote node which sends messages on
600 // channel_index.
Austin Schuh58646e22021-08-23 23:51:46 -0700601 BootTimestamp monotonic_remote_now(size_t channel_index) {
602 State *s = channel_source_state_[channel_index];
603 return BootTimestamp{
604 .boot = s->boot_count(),
605 .time = s->node_event_loop_factory_->monotonic_now()};
Austin Schuh858c9f32020-08-31 16:56:12 -0700606 }
607
Austin Schuh5ee56872021-01-30 16:53:34 -0800608 // Returns the start time of the remote for the provided channel.
609 monotonic_clock::time_point monotonic_remote_start_time(
Austin Schuh58646e22021-08-23 23:51:46 -0700610 size_t boot_count, size_t channel_index) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700611 return channel_source_state_[channel_index]->monotonic_start_time(
612 boot_count);
Austin Schuh5ee56872021-01-30 16:53:34 -0800613 }
614
Austin Schuh58646e22021-08-23 23:51:46 -0700615 void DestroyEventLoop() { event_loop_unique_ptr_.reset(); }
616
617 EventLoop *MakeEventLoop() {
618 CHECK(!event_loop_unique_ptr_);
James Kuszmaul890c2492022-04-06 14:59:31 -0700619 // TODO(james): Enable exclusive senders on LogReader to allow us to
620 // ensure we are remapping channels correctly.
621 event_loop_unique_ptr_ = node_event_loop_factory_->MakeEventLoop(
622 "log_reader", {NodeEventLoopFactory::CheckSentTooFast::kNo,
James Kuszmaul94ca5132022-07-19 09:11:08 -0700623 NodeEventLoopFactory::ExclusiveSenders::kYes,
624 NonExclusiveChannels()});
Austin Schuh58646e22021-08-23 23:51:46 -0700625 return event_loop_unique_ptr_.get();
626 }
627
Austin Schuh2f8fd752020-09-01 22:38:28 -0700628 distributed_clock::time_point RemoteToDistributedClock(
629 size_t channel_index, monotonic_clock::time_point time) {
James Kuszmaul09632422022-05-25 15:56:19 -0700630 CHECK(node_event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700631 return channel_source_state_[channel_index]
632 ->node_event_loop_factory_->ToDistributedClock(time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700633 }
634
635 const Node *remote_node(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700636 return channel_source_state_[channel_index]
637 ->node_event_loop_factory_->node();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700638 }
639
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800640 monotonic_clock::time_point monotonic_now() const {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700641 CHECK_NOTNULL(event_loop_);
James Kuszmaul09632422022-05-25 15:56:19 -0700642 return event_loop_->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700643 }
644
Austin Schuh858c9f32020-08-31 16:56:12 -0700645 // Sets the number of channels.
646 void SetChannelCount(size_t count);
647
648 // Sets the sender, filter, and target factory for a channel.
Austin Schuh969cd602021-01-03 00:09:45 -0800649 void SetChannel(size_t logged_channel_index, size_t factory_channel_index,
650 std::unique_ptr<RawSender> sender,
651 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh58646e22021-08-23 23:51:46 -0700652 bool is_forwarded, State *source_state);
653
654 void SetRemoteTimestampSender(size_t logged_channel_index,
655 RemoteMessageSender *remote_timestamp_sender);
656
657 void RunOnStart();
658 void RunOnEnd();
Austin Schuh858c9f32020-08-31 16:56:12 -0700659
Austin Schuhe33c08d2022-02-03 18:15:21 -0800660 // Handles a logfile start event to potentially call the OnStart callbacks.
661 void NotifyLogfileStart();
662 // Handles a start time flag start event to potentially call the OnStart
663 // callbacks.
664 void NotifyFlagStart();
665
666 // Handles a logfile end event to potentially call the OnEnd callbacks.
667 void NotifyLogfileEnd();
668 // Handles a end time flag start event to potentially call the OnEnd
669 // callbacks.
670 void NotifyFlagEnd();
671
Austin Schuh858c9f32020-08-31 16:56:12 -0700672 // Unregisters everything so we can destory the event loop.
Austin Schuh58646e22021-08-23 23:51:46 -0700673 // TODO(austin): Is this needed? OnShutdown should be able to serve this
674 // need.
Austin Schuh858c9f32020-08-31 16:56:12 -0700675 void Deregister();
676
677 // Sets the current TimerHandle for the replay callback.
678 void set_timer_handler(TimerHandler *timer_handler) {
679 timer_handler_ = timer_handler;
Austin Schuh58646e22021-08-23 23:51:46 -0700680 if (timer_handler_) {
681 if (event_loop_->node() != nullptr) {
682 timer_handler_->set_name(absl::StrCat(
683 event_loop_->node()->name()->string_view(), "_main"));
684 } else {
685 timer_handler_->set_name("main");
686 }
687 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700688 }
689
Austin Schuhe33c08d2022-02-03 18:15:21 -0800690 // Creates and registers the --start_time and --end_time event callbacks.
691 void SetStartTimeFlag(realtime_clock::time_point start_time);
692 void SetEndTimeFlag(realtime_clock::time_point end_time);
693
694 // Notices the next message to update the start/end time callbacks.
695 void ObserveNextMessage(monotonic_clock::time_point monotonic_event,
696 realtime_clock::time_point realtime_event);
697
698 // Clears the start and end time flag handlers so we can delete the event
699 // loop.
700 void ClearTimeFlags();
701
Austin Schuh858c9f32020-08-31 16:56:12 -0700702 // Sets the next wakeup time on the replay callback.
Philipp Schradera6712522023-07-05 20:25:11 -0700703 void Schedule(monotonic_clock::time_point next_time) {
704 timer_handler_->Schedule(
James Kuszmaul8866e642022-06-10 16:00:36 -0700705 std::max(monotonic_now(), next_time + clock_offset()));
Austin Schuh858c9f32020-08-31 16:56:12 -0700706 }
707
708 // Sends a buffer on the provided channel index.
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600709 bool Send(const TimestampedMessage &&timestamped_message);
Austin Schuh858c9f32020-08-31 16:56:12 -0700710
James Kuszmaulc3f34d12022-08-15 15:57:55 -0700711 void MaybeSetClockOffset();
James Kuszmaul09632422022-05-25 15:56:19 -0700712 std::chrono::nanoseconds clock_offset() const { return clock_offset_; }
713
Austin Schuh858c9f32020-08-31 16:56:12 -0700714 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700715 std::string DebugString() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800716 if (!timestamp_mapper_) {
Austin Schuhe639ea12021-01-25 13:00:22 -0800717 return "";
Austin Schuh287d43d2020-12-04 20:19:33 -0800718 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800719 return timestamp_mapper_->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700721
Austin Schuh58646e22021-08-23 23:51:46 -0700722 void ClearRemoteTimestampSenders() {
723 channel_timestamp_loggers_.clear();
724 timestamp_loggers_.clear();
725 }
726
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800727 void SetFoundLastMessage(bool val) {
728 found_last_message_ = val;
729 last_message_.resize(factory_channel_index_.size(), false);
730 }
731 bool found_last_message() const { return found_last_message_; }
732
733 void set_last_message(size_t channel_index) {
734 CHECK_LT(channel_index, last_message_.size());
735 last_message_[channel_index] = true;
736 }
737
738 bool last_message(size_t channel_index) {
739 CHECK_LT(channel_index, last_message_.size());
740 return last_message_[channel_index];
741 }
742
James Kuszmaula16a7912022-06-17 10:58:12 -0700743 void set_timing_accuracy_sender(
744 aos::Sender<timing::ReplayTiming> timing_sender) {
745 timing_statistics_sender_ = std::move(timing_sender);
746 OnEnd([this]() { SendMessageTimings(); });
747 }
748
749 // If running with ThreadedBuffering::kYes, will start the processing thread
750 // and queue up messages until the specified time. No-op of
751 // ThreadedBuffering::kNo is set. Should only be called once.
752 void QueueThreadUntil(BootTimestamp time);
753
Austin Schuh858c9f32020-08-31 16:56:12 -0700754 private:
James Kuszmaulc3f34d12022-08-15 15:57:55 -0700755 void TrackMessageSendTiming(const RawSender &sender,
756 monotonic_clock::time_point expected_send_time);
James Kuszmaula16a7912022-06-17 10:58:12 -0700757 void SendMessageTimings();
Austin Schuh858c9f32020-08-31 16:56:12 -0700758 // Log file.
Austin Schuh287d43d2020-12-04 20:19:33 -0800759 std::unique_ptr<TimestampMapper> timestamp_mapper_;
Austin Schuh63097262023-08-16 17:04:29 -0700760 const TimestampQueueStrategy timestamp_queue_strategy_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700761
Austin Schuh858c9f32020-08-31 16:56:12 -0700762 // Senders.
763 std::vector<std::unique_ptr<RawSender>> channels_;
Austin Schuh969cd602021-01-03 00:09:45 -0800764 std::vector<RemoteMessageSender *> remote_timestamp_senders_;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700765 // The mapping from logged channel index to sent channel index. Needed for
766 // sending out MessageHeaders.
767 std::vector<int> factory_channel_index_;
768
Austin Schuh9942bae2021-01-07 22:06:44 -0800769 struct ContiguousSentTimestamp {
770 // Most timestamps make it through the network, so it saves a ton of
771 // memory and CPU to store the start and end, and search for valid ranges.
772 // For one of the logs I looked at, we had 2 ranges for 4 days.
773 //
774 // Save monotonic times as well to help if a queue index ever wraps. Odds
775 // are very low, but doesn't hurt.
776 //
777 // The starting time and matching queue index.
778 monotonic_clock::time_point starting_monotonic_event_time =
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700779 monotonic_clock::min_time;
Austin Schuh9942bae2021-01-07 22:06:44 -0800780 uint32_t starting_queue_index = 0xffffffff;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700781
Austin Schuh9942bae2021-01-07 22:06:44 -0800782 // Ending time and queue index.
783 monotonic_clock::time_point ending_monotonic_event_time =
784 monotonic_clock::max_time;
785 uint32_t ending_queue_index = 0xffffffff;
786
787 // The queue index that the first message was *actually* sent with. The
788 // queue indices are assumed to be contiguous through this range.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700789 uint32_t actual_queue_index = 0xffffffff;
790 };
791
James Kuszmaul94ca5132022-07-19 09:11:08 -0700792 // Returns a list of channels which LogReader will send on but which may
793 // *also* get sent on by other applications in replay.
794 std::vector<
795 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
796 NonExclusiveChannels();
797
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700798 // Stores all the timestamps that have been sent on this channel. This is
799 // only done for channels which are forwarded and on the node which
Austin Schuh9942bae2021-01-07 22:06:44 -0800800 // initially sends the message. Compress using ranges and offsets.
801 std::vector<std::unique_ptr<std::vector<ContiguousSentTimestamp>>>
802 queue_index_map_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700803
804 // Factory (if we are in sim) that this loop was created on.
805 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800806 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
807
James Kuszmaulb11a1502022-07-01 16:02:25 -0700808 // Callback for when this node hits its realtime end time.
809 std::function<void()> notice_realtime_end_;
810
Austin Schuh858c9f32020-08-31 16:56:12 -0700811 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
812 // Event loop.
Austin Schuh58646e22021-08-23 23:51:46 -0700813 const Node *node_ = nullptr;
Austin Schuh858c9f32020-08-31 16:56:12 -0700814 EventLoop *event_loop_ = nullptr;
815 // And timer used to send messages.
Austin Schuh58646e22021-08-23 23:51:46 -0700816 TimerHandler *timer_handler_ = nullptr;
817 TimerHandler *startup_timer_ = nullptr;
Austin Schuh858c9f32020-08-31 16:56:12 -0700818
Austin Schuhe33c08d2022-02-03 18:15:21 -0800819 std::unique_ptr<EventNotifier> start_event_notifier_;
820 std::unique_ptr<EventNotifier> end_event_notifier_;
821
Austin Schuh8bd96322020-02-13 21:18:22 -0800822 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
823 // This corresponds to the object which is shared among all the channels
824 // going between 2 nodes. The second element in the tuple indicates if this
825 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700826 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
James Kuszmaul09632422022-05-25 15:56:19 -0700827 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800828
Austin Schuh84dd1332023-05-03 13:09:47 -0700829 // List of States (or nullptr if it isn't a forwarded channel) which
830 // correspond to the originating node.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700831 std::vector<State *> channel_source_state_;
832
Austin Schuh61e973f2021-02-21 21:43:56 -0800833 // This is a cache for channel, connection mapping to the corresponding
834 // sender.
835 absl::btree_map<std::pair<const Channel *, const Connection *>,
836 std::shared_ptr<RemoteMessageSender>>
837 channel_timestamp_loggers_;
838
839 // Mapping from resolved RemoteMessage channel to RemoteMessage sender. This
840 // is the channel that timestamps are published to.
841 absl::btree_map<const Channel *, std::shared_ptr<RemoteMessageSender>>
842 timestamp_loggers_;
Austin Schuh58646e22021-08-23 23:51:46 -0700843
James Kuszmaul09632422022-05-25 15:56:19 -0700844 // Time offset between the log's monotonic clock and the current event
845 // loop's monotonic clock. Useful when replaying logs with non-simulated
846 // event loops.
847 std::chrono::nanoseconds clock_offset_{0};
848
Austin Schuh58646e22021-08-23 23:51:46 -0700849 std::vector<std::function<void()>> on_starts_;
850 std::vector<std::function<void()>> on_ends_;
851
James Kuszmaula16a7912022-06-17 10:58:12 -0700852 std::atomic<bool> stopped_ = false;
853 std::atomic<bool> started_ = false;
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800854
855 bool found_last_message_ = false;
856 std::vector<bool> last_message_;
James Kuszmaula16a7912022-06-17 10:58:12 -0700857
858 std::vector<timing::MessageTimingT> send_timings_;
859 aos::Sender<timing::ReplayTiming> timing_statistics_sender_;
860
861 // Protects access to any internal state after Run() is called. Designed
862 // assuming that only one node is actually executing in replay.
863 // Threading design:
864 // * The worker passed to message_queuer_ has full ownership over all
865 // the log-reading code, timestamp filters, last_queued_message_, etc.
866 // * The main thread should only have exclusive access to the replay
867 // event loop and associated features (mainly senders).
868 // It will pop an item out of the queue (which does maintain a shared_ptr
869 // reference which may also be being used by the message_queuer_ thread,
870 // but having shared_ptr's accessing the same memory from
871 // separate threads is permissible).
872 // Enabling this in simulation is currently infeasible due to a lack of
873 // synchronization in the MultiNodeNoncausalOffsetEstimator. Essentially,
874 // when the message_queuer_ thread attempts to read/pop messages from the
875 // timestamp_mapper_, it will end up calling callbacks that update the
876 // internal state of the MultiNodeNoncausalOffsetEstimator. Simultaneously,
877 // the event scheduler that is running in the main thread to orchestrate the
878 // simulation will be querying the estimator to know what the clocks on the
879 // various nodes are at, leading to potential issues.
880 ThreadedBuffering threading_;
881 std::optional<BootTimestamp> last_queued_message_;
882 std::optional<util::ThreadedQueue<TimestampedMessage, BootTimestamp>>
883 message_queuer_;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700884
885 // If a ReplayChannels was passed to LogReader, this will hold the
886 // indices of the channels to replay for the Node represented by
887 // the instance of LogReader::State.
Naman Guptacf6d4422023-03-01 11:41:00 -0800888 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices_;
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600889 const std::vector<std::function<void(void *message)>>
890 before_send_callbacks_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800891 };
892
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600893 // Checks if any of the States have been constructed yet.
894 // This happens during Register
895 bool AreStatesInitialized() const;
896
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700897 // If a ReplayChannels was passed to LogReader then creates a
Naman Guptacf6d4422023-03-01 11:41:00 -0800898 // ReplayChannelIndices for the given node. Otherwise, returns a nullptr.
899 std::unique_ptr<const ReplayChannelIndices> MaybeMakeReplayChannelIndices(
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700900 const Node *node);
901
Austin Schuh8bd96322020-02-13 21:18:22 -0800902 // Node index -> State.
903 std::vector<std::unique_ptr<State>> states_;
904
905 // Creates the requested filter if it doesn't exist, regardless of whether
906 // these nodes can actually communicate directly. The second return value
907 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700908 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
909 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800910
Austin Schuh63097262023-08-16 17:04:29 -0700911 // Returns the timestamp queueing strategy to use.
912 TimestampQueueStrategy ComputeTimestampQueueStrategy() const;
913
Austin Schuh8bd96322020-02-13 21:18:22 -0800914 // List of filters for a connection. The pointer to the first node will be
915 // less than the second node.
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800916 std::unique_ptr<message_bridge::MultiNodeNoncausalOffsetEstimator> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800917
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800918 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
919 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800920
Austin Schuh6f3babe2020-01-26 20:34:50 -0800921 // Number of nodes which still have data to send. This is used to figure out
922 // when to exit.
923 size_t live_nodes_ = 0;
924
James Kuszmaulb11a1502022-07-01 16:02:25 -0700925 // Similar counter to live_nodes_, but for tracking which individual nodes are
926 // running and have yet to hit the realtime end time, if any.
927 size_t live_nodes_with_realtime_time_end_ = 0;
928
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800929 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800930
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700931 // If a ReplayChannels was passed to LogReader, this will hold the
932 // name and type of channels to replay which is used when creating States.
933 const ReplayChannels *replay_channels_ = nullptr;
934
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600935 // The callbacks that will be called before sending a message indexed by the
936 // channel index from the logged_configuration
937 std::vector<std::function<void(void *message)>> before_send_callbacks_;
938
Austin Schuhcde938c2020-02-02 17:30:07 -0800939 // If true, the replay timer will ignore any missing data. This is used
940 // during startup when we are bootstrapping everything and trying to get to
941 // the start of all the log files.
942 bool ignore_missing_data_ = false;
James Kuszmaul71a81932020-12-15 21:08:01 -0800943
944 // Whether to exit the SimulatedEventLoop when we finish reading the logs.
945 bool exit_on_finish_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800946
947 realtime_clock::time_point start_time_ = realtime_clock::min_time;
948 realtime_clock::time_point end_time_ = realtime_clock::max_time;
Eric Schmiedeberge279b532023-04-19 16:36:02 -0600949 ConfigRemapper config_remapper_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800950};
951
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -0800952} // namespace aos::logger
Austin Schuhe309d2a2019-11-29 13:25:21 -0800953
Austin Schuhb06f03b2021-02-17 22:00:37 -0800954#endif // AOS_EVENTS_LOGGING_LOG_READER_H_