blob: 196ac53c1e901e2eb0837ba52551007e7ecae9ac [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>
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 Schuhe309d2a2019-11-29 13:25:21 -080010#include "aos/events/event_loop.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070011#include "aos/events/logging/logfile_sorting.h"
Austin Schuha36c8902019-12-30 18:07:15 -080012#include "aos/events/logging/logfile_utils.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080013#include "aos/events/logging/logger_generated.h"
Austin Schuh92547522019-12-28 14:33:43 -080014#include "aos/events/simulated_event_loop.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070015#include "aos/network/message_bridge_server_generated.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080016#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080017#include "aos/network/remote_message_generated.h"
Austin Schuh8bd96322020-02-13 21:18:22 -080018#include "aos/network/timestamp_filter.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080019#include "aos/time/time.h"
Austin Schuh4385b142021-03-14 21:31:13 -070020#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080021#include "flatbuffers/flatbuffers.h"
22
23namespace aos {
24namespace logger {
25
Austin Schuhe33c08d2022-02-03 18:15:21 -080026class EventNotifier;
27
Austin Schuh6f3babe2020-01-26 20:34:50 -080028// We end up with one of the following 3 log file types.
29//
30// Single node logged as the source node.
31// -> Replayed just on the source node.
32//
33// Forwarding timestamps only logged from the perspective of the destination
34// node.
35// -> Matched with data on source node and logged.
36//
37// Forwarding timestamps with data logged as the destination node.
38// -> Replayed just as the destination
39// -> Replayed as the source (Much harder, ordering is not defined)
40//
41// Duplicate data logged. -> CHECK that it matches and explode otherwise.
42//
43// This can be boiled down to a set of constraints and tools.
44//
45// 1) Forwarding timestamps and data need to be logged separately.
46// 2) Any forwarded data logged on the destination node needs to be logged
47// separately such that it can be sorted.
48//
49// 1) Log reader needs to be able to sort a list of log files.
50// 2) Log reader needs to be able to merge sorted lists of log files.
51// 3) Log reader needs to be able to match timestamps with messages.
52//
53// We also need to be able to generate multiple views of a log file depending on
54// the target.
55
Austin Schuhe309d2a2019-11-29 13:25:21 -080056// Replays all the channels in the logfile to the event loop.
57class LogReader {
58 public:
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -080059 // If you want to supply a new configuration that will be used for replay
60 // (e.g., to change message rates, or to populate an updated schema), then
61 // pass it in here. It must provide all the channels that the original logged
62 // config did.
Austin Schuh6f3babe2020-01-26 20:34:50 -080063 //
Austin Schuh287d43d2020-12-04 20:19:33 -080064 // The single file constructor calls SortParts internally.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -080065 LogReader(std::string_view filename,
66 const Configuration *replay_configuration = nullptr);
Austin Schuh287d43d2020-12-04 20:19:33 -080067 LogReader(std::vector<LogFile> log_files,
Austin Schuh11d43732020-09-21 17:28:30 -070068 const Configuration *replay_configuration = nullptr);
James Kuszmaul7daef362019-12-31 18:28:17 -080069 ~LogReader();
Austin Schuhe309d2a2019-11-29 13:25:21 -080070
Austin Schuh6331ef92020-01-07 18:28:09 -080071 // Registers all the callbacks to send the log file data out on an event loop
72 // created in event_loop_factory. This also updates time to be at the start
73 // of the log file by running until the log file starts.
74 // Note: the configuration used in the factory should be configuration()
75 // below, but can be anything as long as the locations needed to send
76 // everything are available.
James Kuszmaul84ff3e52020-01-03 19:48:53 -080077 void Register(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -080078
Austin Schuh58646e22021-08-23 23:51:46 -070079 // Registers all the callbacks to send the log file data out to an event loop
80 // factory. This does not start replaying or change the current distributed
81 // time of the factory. It does change the monotonic clocks to be right.
82 void RegisterWithoutStarting(SimulatedEventLoopFactory *event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -080083 // Runs the log until the last start time. Register above is defined as:
84 // Register(...) {
85 // RegisterWithoutStarting
86 // StartAfterRegister
87 // }
88 // This should generally be considered as a stepping stone to convert from
89 // Register() to RegisterWithoutStarting() incrementally.
90 void StartAfterRegister(SimulatedEventLoopFactory *event_loop_factory);
91
Austin Schuh6331ef92020-01-07 18:28:09 -080092 // Creates an SimulatedEventLoopFactory accessible via event_loop_factory(),
93 // and then calls Register.
94 void Register();
95 // Registers callbacks for all the events after the log file starts. This is
96 // only useful when replaying live.
Austin Schuhe309d2a2019-11-29 13:25:21 -080097 void Register(EventLoop *event_loop);
Austin Schuh6331ef92020-01-07 18:28:09 -080098
Austin Schuh58646e22021-08-23 23:51:46 -070099 // Called whenever a log file starts for a node.
100 void OnStart(std::function<void()> fn);
101 void OnStart(const Node *node, std::function<void()> fn);
102 // Called whenever a log file ends for a node.
103 void OnEnd(std::function<void()> fn);
104 void OnEnd(const Node *node, std::function<void()> fn);
105
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800106 // Unregisters the senders. You only need to call this if you separately
107 // supplied an event loop or event loop factory and the lifetimes are such
108 // that they need to be explicitly destroyed before the LogReader destructor
109 // gets called.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800110 void Deregister();
111
Austin Schuh0c297012020-09-16 18:41:59 -0700112 // Returns the configuration being used for replay from the log file.
113 // Note that this may be different from the configuration actually used for
114 // handling events. You should generally only use this to create a
115 // SimulatedEventLoopFactory, and then get the configuration from there for
116 // everything else.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800117 const Configuration *logged_configuration() const;
Austin Schuh11d43732020-09-21 17:28:30 -0700118 // Returns the configuration being used for replay from the log file.
119 // Note that this may be different from the configuration actually used for
120 // handling events. You should generally only use this to create a
121 // SimulatedEventLoopFactory, and then get the configuration from there for
122 // everything else.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800123 // The pointer is invalidated whenever RemapLoggedChannel is called.
Austin Schuh15649d62019-12-28 16:36:38 -0800124 const Configuration *configuration() const;
125
Austin Schuh6f3babe2020-01-26 20:34:50 -0800126 // Returns the nodes that this log file was created on. This is a list of
Austin Schuh07676622021-01-21 18:59:17 -0800127 // pointers to a node in the nodes() list inside logged_configuration().
128 std::vector<const Node *> LoggedNodes() const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800129
130 // Returns the starting timestamp for the log file.
Austin Schuh11d43732020-09-21 17:28:30 -0700131 monotonic_clock::time_point monotonic_start_time(
132 const Node *node = nullptr) const;
133 realtime_clock::time_point realtime_start_time(
134 const Node *node = nullptr) const;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800135
Austin Schuhe33c08d2022-02-03 18:15:21 -0800136 // Sets the start and end times to replay data until for all nodes. This
137 // overrides the --start_time and --end_time flags. The default is to replay
138 // all data.
139 void SetStartTime(std::string start_time);
140 void SetStartTime(realtime_clock::time_point start_time);
141 void SetEndTime(std::string end_time);
142 void SetEndTime(realtime_clock::time_point end_time);
143
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800144 // Causes the logger to publish the provided channel on a different name so
145 // that replayed applications can publish on the proper channel name without
146 // interference. This operates on raw channel names, without any node or
147 // application specific mappings.
148 void RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800149 std::string_view add_prefix = "/original",
150 std::string_view new_type = "");
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800151 template <typename T>
152 void RemapLoggedChannel(std::string_view name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800153 std::string_view add_prefix = "/original",
154 std::string_view new_type = "") {
155 RemapLoggedChannel(name, T::GetFullyQualifiedName(), add_prefix, new_type);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800156 }
157
Austin Schuh01b4c352020-09-21 23:09:39 -0700158 // Remaps the provided channel, though this respects node mappings, and
159 // preserves them too. This makes it so if /aos -> /pi1/aos on one node,
160 // /original/aos -> /original/pi1/aos on the same node after renaming, just
Austin Schuh0de30f32020-12-06 12:44:28 -0800161 // like you would hope. If new_type is not empty, the new channel will use
162 // the provided type instead. This allows for renaming messages.
Austin Schuh01b4c352020-09-21 23:09:39 -0700163 //
164 // TODO(austin): If you have 2 nodes remapping something to the same channel,
165 // this doesn't handle that. No use cases exist yet for that, so it isn't
166 // being done yet.
167 void RemapLoggedChannel(std::string_view name, std::string_view type,
168 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800169 std::string_view add_prefix = "/original",
170 std::string_view new_type = "");
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700171 template <typename T>
Austin Schuh01b4c352020-09-21 23:09:39 -0700172 void RemapLoggedChannel(std::string_view name, const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800173 std::string_view add_prefix = "/original",
174 std::string_view new_type = "") {
175 RemapLoggedChannel(name, T::GetFullyQualifiedName(), node, add_prefix,
176 new_type);
Austin Schuh01b4c352020-09-21 23:09:39 -0700177 }
178
179 template <typename T>
180 bool HasChannel(std::string_view name, const Node *node = nullptr) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800181 return configuration::GetChannel(logged_configuration(), name,
Austin Schuh0de30f32020-12-06 12:44:28 -0800182 T::GetFullyQualifiedName(), "", node,
183 true) != nullptr;
Brian Silvermande9f3ff2020-04-28 16:56:58 -0700184 }
185
Austin Schuh82529062021-12-08 12:09:52 -0800186 template <typename T>
187 void MaybeRemapLoggedChannel(std::string_view name,
188 const Node *node = nullptr) {
189 if (HasChannel<T>(name, node)) {
190 RemapLoggedChannel<T>(name, node);
191 }
192 }
193
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800194 // Returns true if the channel exists on the node and was logged.
195 template <typename T>
196 bool HasLoggedChannel(std::string_view name, const Node *node = nullptr) {
Austin Schuh5ee56872021-01-30 16:53:34 -0800197 const Channel *channel =
198 configuration::GetChannel(logged_configuration(), name,
199 T::GetFullyQualifiedName(), "", node, true);
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800200 if (channel == nullptr) return false;
201 return channel->logger() != LoggerConfig::NOT_LOGGED;
202 }
203
Austin Schuh1c227352021-09-17 12:53:54 -0700204 // Returns a list of all the original channels from remapping.
205 std::vector<const Channel *> RemappedChannels() const;
206
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800207 SimulatedEventLoopFactory *event_loop_factory() {
208 return event_loop_factory_;
209 }
210
Austin Schuh0ca51f32020-12-25 21:51:45 -0800211 std::string_view name() const { return log_files_[0].name; }
Austin Schuh0c297012020-09-16 18:41:59 -0700212
James Kuszmaul71a81932020-12-15 21:08:01 -0800213 // Set whether to exit the SimulatedEventLoopFactory when we finish reading
214 // the logfile.
215 void set_exit_on_finish(bool exit_on_finish) {
216 exit_on_finish_ = exit_on_finish;
217 }
218
Austin Schuhe309d2a2019-11-29 13:25:21 -0800219 private:
Austin Schuh58646e22021-08-23 23:51:46 -0700220 void Register(EventLoop *event_loop, const Node *node);
221
222 void RegisterDuringStartup(EventLoop *event_loop, const Node *node);
223
224 const Channel *RemapChannel(const EventLoop *event_loop, const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -0800225 const Channel *channel);
226
Austin Schuhe309d2a2019-11-29 13:25:21 -0800227 // Queues at least max_out_of_order_duration_ messages into channels_.
228 void QueueMessages();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800229 // Handle constructing a configuration with all the additional remapped
230 // channels from calls to RemapLoggedChannel.
231 void MakeRemappedConfig();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800232
Austin Schuh2f8fd752020-09-01 22:38:28 -0700233 // Returns the number of nodes.
234 size_t nodes_count() const {
235 return !configuration::MultiNode(logged_configuration())
236 ? 1u
237 : logged_configuration()->nodes()->size();
238 }
239
Austin Schuh287d43d2020-12-04 20:19:33 -0800240 const std::vector<LogFile> log_files_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800241
Austin Schuh969cd602021-01-03 00:09:45 -0800242 // Class to manage sending RemoteMessages on the provided node after the
243 // correct delay.
Austin Schuh5ee56872021-01-30 16:53:34 -0800244 class RemoteMessageSender {
Austin Schuh969cd602021-01-03 00:09:45 -0800245 public:
246 RemoteMessageSender(aos::Sender<message_bridge::RemoteMessage> sender,
247 EventLoop *event_loop);
248 RemoteMessageSender(RemoteMessageSender const &) = delete;
249 RemoteMessageSender &operator=(RemoteMessageSender const &) = delete;
250
251 // Sends the provided message. If monotonic_timestamp_time is min_time,
252 // send it immediately.
253 void Send(
254 FlatbufferDetachedBuffer<message_bridge::RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -0700255 BootTimestamp monotonic_timestamp_time, size_t source_boot_count);
Austin Schuh969cd602021-01-03 00:09:45 -0800256
257 private:
258 // Handles actually sending the timestamp if we were delayed.
259 void SendTimestamp();
260 // Handles scheduling the timer to send at the correct time.
261 void ScheduleTimestamp();
262
263 EventLoop *event_loop_;
264 aos::Sender<message_bridge::RemoteMessage> sender_;
265 aos::TimerHandler *timer_;
266
267 // Time we are scheduled for, or min_time if we aren't scheduled.
268 monotonic_clock::time_point scheduled_time_ = monotonic_clock::min_time;
269
270 struct Timestamp {
271 Timestamp(FlatbufferDetachedBuffer<message_bridge::RemoteMessage>
272 new_remote_message,
273 monotonic_clock::time_point new_monotonic_timestamp_time)
274 : remote_message(std::move(new_remote_message)),
275 monotonic_timestamp_time(new_monotonic_timestamp_time) {}
276 FlatbufferDetachedBuffer<message_bridge::RemoteMessage> remote_message;
277 monotonic_clock::time_point monotonic_timestamp_time;
278 };
279
280 // List of messages to send. The timer works through them and then disables
281 // itself automatically.
282 std::deque<Timestamp> remote_timestamps_;
283 };
284
Austin Schuh6f3babe2020-01-26 20:34:50 -0800285 // State per node.
Austin Schuh858c9f32020-08-31 16:56:12 -0700286 class State {
287 public:
Austin Schuh58646e22021-08-23 23:51:46 -0700288 State(std::unique_ptr<TimestampMapper> timestamp_mapper, const Node *node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800289
290 // Connects up the timestamp mappers.
291 void AddPeer(State *peer);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800292
Austin Schuhe639ea12021-01-25 13:00:22 -0800293 TimestampMapper *timestamp_mapper() { return timestamp_mapper_.get(); }
294
Austin Schuhdda74ec2021-01-03 19:30:37 -0800295 // Returns the next sorted message with all the timestamps extracted and
296 // matched.
297 TimestampedMessage PopOldest();
Austin Schuh188eabe2020-12-29 23:41:13 -0800298
Austin Schuh858c9f32020-08-31 16:56:12 -0700299 // Returns the monotonic time of the oldest message.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800300 BootTimestamp OldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -0700301
302 size_t boot_count() const {
303 // If we are replaying directly into an event loop, we can't reboot. So
304 // we will stay stuck on the 0th boot.
305 if (!node_event_loop_factory_) return 0u;
306 return node_event_loop_factory_->boot_count();
307 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700308
309 // Primes the queues inside State. Should be called before calling
310 // OldestMessageTime.
311 void SeedSortedMessages();
Austin Schuh8bd96322020-02-13 21:18:22 -0800312
Austin Schuh58646e22021-08-23 23:51:46 -0700313 void SetupStartupTimer() {
314 const monotonic_clock::time_point start_time =
315 monotonic_start_time(boot_count());
316 if (start_time == monotonic_clock::min_time) {
317 LOG(ERROR)
318 << "No start time, skipping, please figure out when this happens";
Austin Schuhe33c08d2022-02-03 18:15:21 -0800319 NotifyLogfileStart();
Austin Schuh58646e22021-08-23 23:51:46 -0700320 return;
321 }
James Kuszmaul57d39742021-10-15 20:07:34 -0700322 CHECK_GE(start_time, event_loop_->monotonic_now());
Austin Schuh58646e22021-08-23 23:51:46 -0700323 startup_timer_->Setup(start_time);
324 }
325
326 void set_startup_timer(TimerHandler *timer_handler) {
327 startup_timer_ = timer_handler;
328 if (startup_timer_) {
329 if (event_loop_->node() != nullptr) {
330 startup_timer_->set_name(absl::StrCat(
331 event_loop_->node()->name()->string_view(), "_startup"));
332 } else {
333 startup_timer_->set_name("startup");
334 }
335 }
336 }
337
Austin Schuh858c9f32020-08-31 16:56:12 -0700338 // Returns the starting time for this node.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700339 monotonic_clock::time_point monotonic_start_time(size_t boot_count) const {
340 return timestamp_mapper_
341 ? timestamp_mapper_->monotonic_start_time(boot_count)
342 : monotonic_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700343 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700344 realtime_clock::time_point realtime_start_time(size_t boot_count) const {
345 return timestamp_mapper_
346 ? timestamp_mapper_->realtime_start_time(boot_count)
347 : realtime_clock::min_time;
Austin Schuh858c9f32020-08-31 16:56:12 -0700348 }
349
350 // Sets the node event loop factory for replaying into a
351 // SimulatedEventLoopFactory. Returns the EventLoop to use.
Austin Schuhe33c08d2022-02-03 18:15:21 -0800352 void SetNodeEventLoopFactory(
353 NodeEventLoopFactory *node_event_loop_factory,
354 SimulatedEventLoopFactory *event_loop_factory);
Austin Schuh858c9f32020-08-31 16:56:12 -0700355
356 // Sets and gets the event loop to use.
357 void set_event_loop(EventLoop *event_loop) { event_loop_ = event_loop; }
358 EventLoop *event_loop() { return event_loop_; }
359
Austin Schuh58646e22021-08-23 23:51:46 -0700360 const Node *node() const { return node_; }
361
362 void Register(EventLoop *event_loop);
363
364 void OnStart(std::function<void()> fn);
365 void OnEnd(std::function<void()> fn);
366
Austin Schuh858c9f32020-08-31 16:56:12 -0700367 // Sets the current realtime offset from the monotonic clock for this node
368 // (if we are on a simulated event loop).
369 void SetRealtimeOffset(monotonic_clock::time_point monotonic_time,
370 realtime_clock::time_point realtime_time) {
371 if (node_event_loop_factory_ != nullptr) {
372 node_event_loop_factory_->SetRealtimeOffset(monotonic_time,
373 realtime_time);
374 }
375 }
376
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700377 // Returns the MessageHeader sender to log delivery timestamps to for the
378 // provided remote node.
Austin Schuh61e973f2021-02-21 21:43:56 -0800379 RemoteMessageSender *RemoteTimestampSender(const Channel *channel,
380 const Connection *connection);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700381
Austin Schuh858c9f32020-08-31 16:56:12 -0700382 // Converts a timestamp from the monotonic clock on this node to the
383 // distributed clock.
384 distributed_clock::time_point ToDistributedClock(
385 monotonic_clock::time_point time) {
386 return node_event_loop_factory_->ToDistributedClock(time);
387 }
388
Austin Schuh858c9f32020-08-31 16:56:12 -0700389 // Returns the current time on the remote node which sends messages on
390 // channel_index.
Austin Schuh58646e22021-08-23 23:51:46 -0700391 BootTimestamp monotonic_remote_now(size_t channel_index) {
392 State *s = channel_source_state_[channel_index];
393 return BootTimestamp{
394 .boot = s->boot_count(),
395 .time = s->node_event_loop_factory_->monotonic_now()};
Austin Schuh858c9f32020-08-31 16:56:12 -0700396 }
397
Austin Schuh5ee56872021-01-30 16:53:34 -0800398 // Returns the start time of the remote for the provided channel.
399 monotonic_clock::time_point monotonic_remote_start_time(
Austin Schuh58646e22021-08-23 23:51:46 -0700400 size_t boot_count, size_t channel_index) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700401 return channel_source_state_[channel_index]->monotonic_start_time(
402 boot_count);
Austin Schuh5ee56872021-01-30 16:53:34 -0800403 }
404
Austin Schuh58646e22021-08-23 23:51:46 -0700405 void DestroyEventLoop() { event_loop_unique_ptr_.reset(); }
406
407 EventLoop *MakeEventLoop() {
408 CHECK(!event_loop_unique_ptr_);
James Kuszmaul890c2492022-04-06 14:59:31 -0700409 // TODO(james): Enable exclusive senders on LogReader to allow us to
410 // ensure we are remapping channels correctly.
411 event_loop_unique_ptr_ = node_event_loop_factory_->MakeEventLoop(
412 "log_reader", {NodeEventLoopFactory::CheckSentTooFast::kNo,
413 NodeEventLoopFactory::ExclusiveSenders::kNo});
Austin Schuh58646e22021-08-23 23:51:46 -0700414 return event_loop_unique_ptr_.get();
415 }
416
Austin Schuh2f8fd752020-09-01 22:38:28 -0700417 distributed_clock::time_point RemoteToDistributedClock(
418 size_t channel_index, monotonic_clock::time_point time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700419 return channel_source_state_[channel_index]
420 ->node_event_loop_factory_->ToDistributedClock(time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700421 }
422
423 const Node *remote_node(size_t channel_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700424 return channel_source_state_[channel_index]
425 ->node_event_loop_factory_->node();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700426 }
427
Stephan Pleines559fa6c2022-01-06 17:23:51 -0800428 monotonic_clock::time_point monotonic_now() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700429 return node_event_loop_factory_->monotonic_now();
430 }
431
Austin Schuh858c9f32020-08-31 16:56:12 -0700432 // Sets the number of channels.
433 void SetChannelCount(size_t count);
434
435 // Sets the sender, filter, and target factory for a channel.
Austin Schuh969cd602021-01-03 00:09:45 -0800436 void SetChannel(size_t logged_channel_index, size_t factory_channel_index,
437 std::unique_ptr<RawSender> sender,
438 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh58646e22021-08-23 23:51:46 -0700439 bool is_forwarded, State *source_state);
440
441 void SetRemoteTimestampSender(size_t logged_channel_index,
442 RemoteMessageSender *remote_timestamp_sender);
443
444 void RunOnStart();
445 void RunOnEnd();
Austin Schuh858c9f32020-08-31 16:56:12 -0700446
Austin Schuhe33c08d2022-02-03 18:15:21 -0800447 // Handles a logfile start event to potentially call the OnStart callbacks.
448 void NotifyLogfileStart();
449 // Handles a start time flag start event to potentially call the OnStart
450 // callbacks.
451 void NotifyFlagStart();
452
453 // Handles a logfile end event to potentially call the OnEnd callbacks.
454 void NotifyLogfileEnd();
455 // Handles a end time flag start event to potentially call the OnEnd
456 // callbacks.
457 void NotifyFlagEnd();
458
Austin Schuh858c9f32020-08-31 16:56:12 -0700459 // Unregisters everything so we can destory the event loop.
Austin Schuh58646e22021-08-23 23:51:46 -0700460 // TODO(austin): Is this needed? OnShutdown should be able to serve this
461 // need.
Austin Schuh858c9f32020-08-31 16:56:12 -0700462 void Deregister();
463
464 // Sets the current TimerHandle for the replay callback.
465 void set_timer_handler(TimerHandler *timer_handler) {
466 timer_handler_ = timer_handler;
Austin Schuh58646e22021-08-23 23:51:46 -0700467 if (timer_handler_) {
468 if (event_loop_->node() != nullptr) {
469 timer_handler_->set_name(absl::StrCat(
470 event_loop_->node()->name()->string_view(), "_main"));
471 } else {
472 timer_handler_->set_name("main");
473 }
474 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700475 }
476
Austin Schuhe33c08d2022-02-03 18:15:21 -0800477 // Creates and registers the --start_time and --end_time event callbacks.
478 void SetStartTimeFlag(realtime_clock::time_point start_time);
479 void SetEndTimeFlag(realtime_clock::time_point end_time);
480
481 // Notices the next message to update the start/end time callbacks.
482 void ObserveNextMessage(monotonic_clock::time_point monotonic_event,
483 realtime_clock::time_point realtime_event);
484
485 // Clears the start and end time flag handlers so we can delete the event
486 // loop.
487 void ClearTimeFlags();
488
Austin Schuh858c9f32020-08-31 16:56:12 -0700489 // Sets the next wakeup time on the replay callback.
490 void Setup(monotonic_clock::time_point next_time) {
491 timer_handler_->Setup(next_time);
492 }
493
494 // Sends a buffer on the provided channel index.
Austin Schuh287d43d2020-12-04 20:19:33 -0800495 bool Send(const TimestampedMessage &timestamped_message);
Austin Schuh858c9f32020-08-31 16:56:12 -0700496
497 // Returns a debug string for the channel merger.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700498 std::string DebugString() const {
Austin Schuh287d43d2020-12-04 20:19:33 -0800499 if (!timestamp_mapper_) {
Austin Schuhe639ea12021-01-25 13:00:22 -0800500 return "";
Austin Schuh287d43d2020-12-04 20:19:33 -0800501 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800502 return timestamp_mapper_->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700503 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700504
Austin Schuh58646e22021-08-23 23:51:46 -0700505 void ClearRemoteTimestampSenders() {
506 channel_timestamp_loggers_.clear();
507 timestamp_loggers_.clear();
508 }
509
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800510 void SetFoundLastMessage(bool val) {
511 found_last_message_ = val;
512 last_message_.resize(factory_channel_index_.size(), false);
513 }
514 bool found_last_message() const { return found_last_message_; }
515
516 void set_last_message(size_t channel_index) {
517 CHECK_LT(channel_index, last_message_.size());
518 last_message_[channel_index] = true;
519 }
520
521 bool last_message(size_t channel_index) {
522 CHECK_LT(channel_index, last_message_.size());
523 return last_message_[channel_index];
524 }
525
Austin Schuh858c9f32020-08-31 16:56:12 -0700526 private:
527 // Log file.
Austin Schuh287d43d2020-12-04 20:19:33 -0800528 std::unique_ptr<TimestampMapper> timestamp_mapper_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700529
Austin Schuh858c9f32020-08-31 16:56:12 -0700530 // Senders.
531 std::vector<std::unique_ptr<RawSender>> channels_;
Austin Schuh969cd602021-01-03 00:09:45 -0800532 std::vector<RemoteMessageSender *> remote_timestamp_senders_;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700533 // The mapping from logged channel index to sent channel index. Needed for
534 // sending out MessageHeaders.
535 std::vector<int> factory_channel_index_;
536
Austin Schuh9942bae2021-01-07 22:06:44 -0800537 struct ContiguousSentTimestamp {
538 // Most timestamps make it through the network, so it saves a ton of
539 // memory and CPU to store the start and end, and search for valid ranges.
540 // For one of the logs I looked at, we had 2 ranges for 4 days.
541 //
542 // Save monotonic times as well to help if a queue index ever wraps. Odds
543 // are very low, but doesn't hurt.
544 //
545 // The starting time and matching queue index.
546 monotonic_clock::time_point starting_monotonic_event_time =
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700547 monotonic_clock::min_time;
Austin Schuh9942bae2021-01-07 22:06:44 -0800548 uint32_t starting_queue_index = 0xffffffff;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700549
Austin Schuh9942bae2021-01-07 22:06:44 -0800550 // Ending time and queue index.
551 monotonic_clock::time_point ending_monotonic_event_time =
552 monotonic_clock::max_time;
553 uint32_t ending_queue_index = 0xffffffff;
554
555 // The queue index that the first message was *actually* sent with. The
556 // queue indices are assumed to be contiguous through this range.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700557 uint32_t actual_queue_index = 0xffffffff;
558 };
559
560 // Stores all the timestamps that have been sent on this channel. This is
561 // only done for channels which are forwarded and on the node which
Austin Schuh9942bae2021-01-07 22:06:44 -0800562 // initially sends the message. Compress using ranges and offsets.
563 std::vector<std::unique_ptr<std::vector<ContiguousSentTimestamp>>>
564 queue_index_map_;
Austin Schuh858c9f32020-08-31 16:56:12 -0700565
566 // Factory (if we are in sim) that this loop was created on.
567 NodeEventLoopFactory *node_event_loop_factory_ = nullptr;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800568 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
569
Austin Schuh858c9f32020-08-31 16:56:12 -0700570 std::unique_ptr<EventLoop> event_loop_unique_ptr_;
571 // Event loop.
Austin Schuh58646e22021-08-23 23:51:46 -0700572 const Node *node_ = nullptr;
Austin Schuh858c9f32020-08-31 16:56:12 -0700573 EventLoop *event_loop_ = nullptr;
574 // And timer used to send messages.
Austin Schuh58646e22021-08-23 23:51:46 -0700575 TimerHandler *timer_handler_ = nullptr;
576 TimerHandler *startup_timer_ = nullptr;
Austin Schuh858c9f32020-08-31 16:56:12 -0700577
Austin Schuhe33c08d2022-02-03 18:15:21 -0800578 std::unique_ptr<EventNotifier> start_event_notifier_;
579 std::unique_ptr<EventNotifier> end_event_notifier_;
580
Austin Schuh8bd96322020-02-13 21:18:22 -0800581 // Filters (or nullptr if it isn't a forwarded channel) for each channel.
582 // This corresponds to the object which is shared among all the channels
583 // going between 2 nodes. The second element in the tuple indicates if this
584 // is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700585 std::vector<message_bridge::NoncausalOffsetEstimator *> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800586
587 // List of NodeEventLoopFactorys (or nullptr if it isn't a forwarded
588 // channel) which correspond to the originating node.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700589 std::vector<State *> channel_source_state_;
590
Austin Schuh61e973f2021-02-21 21:43:56 -0800591 // This is a cache for channel, connection mapping to the corresponding
592 // sender.
593 absl::btree_map<std::pair<const Channel *, const Connection *>,
594 std::shared_ptr<RemoteMessageSender>>
595 channel_timestamp_loggers_;
596
597 // Mapping from resolved RemoteMessage channel to RemoteMessage sender. This
598 // is the channel that timestamps are published to.
599 absl::btree_map<const Channel *, std::shared_ptr<RemoteMessageSender>>
600 timestamp_loggers_;
Austin Schuh58646e22021-08-23 23:51:46 -0700601
602 std::vector<std::function<void()>> on_starts_;
603 std::vector<std::function<void()>> on_ends_;
604
605 bool stopped_ = false;
606 bool started_ = false;
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800607
608 bool found_last_message_ = false;
609 std::vector<bool> last_message_;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800610 };
611
Austin Schuh8bd96322020-02-13 21:18:22 -0800612 // Node index -> State.
613 std::vector<std::unique_ptr<State>> states_;
614
615 // Creates the requested filter if it doesn't exist, regardless of whether
616 // these nodes can actually communicate directly. The second return value
617 // reports if this is the primary direction or not.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700618 message_bridge::NoncausalOffsetEstimator *GetFilter(const Node *node_a,
619 const Node *node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800620
Austin Schuh8bd96322020-02-13 21:18:22 -0800621 // List of filters for a connection. The pointer to the first node will be
622 // less than the second node.
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800623 std::unique_ptr<message_bridge::MultiNodeNoncausalOffsetEstimator> filters_;
Austin Schuh8bd96322020-02-13 21:18:22 -0800624
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800625 std::unique_ptr<FlatbufferDetachedBuffer<Configuration>>
626 remapped_configuration_buffer_;
627
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800628 std::unique_ptr<SimulatedEventLoopFactory> event_loop_factory_unique_ptr_;
629 SimulatedEventLoopFactory *event_loop_factory_ = nullptr;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800630
631 // Map of channel indices to new name. The channel index will be an index into
632 // logged_configuration(), and the string key will be the name of the channel
633 // to send on instead of the logged channel name.
Austin Schuh0de30f32020-12-06 12:44:28 -0800634 struct RemappedChannel {
635 std::string remapped_name;
636 std::string new_type;
637 };
638 std::map<size_t, RemappedChannel> remapped_channels_;
Austin Schuh01b4c352020-09-21 23:09:39 -0700639 std::vector<MapT> maps_;
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800640
Austin Schuh6f3babe2020-01-26 20:34:50 -0800641 // Number of nodes which still have data to send. This is used to figure out
642 // when to exit.
643 size_t live_nodes_ = 0;
644
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800645 const Configuration *remapped_configuration_ = nullptr;
646 const Configuration *replay_configuration_ = nullptr;
Austin Schuhcde938c2020-02-02 17:30:07 -0800647
648 // If true, the replay timer will ignore any missing data. This is used
649 // during startup when we are bootstrapping everything and trying to get to
650 // the start of all the log files.
651 bool ignore_missing_data_ = false;
James Kuszmaul71a81932020-12-15 21:08:01 -0800652
653 // Whether to exit the SimulatedEventLoop when we finish reading the logs.
654 bool exit_on_finish_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800655
656 realtime_clock::time_point start_time_ = realtime_clock::min_time;
657 realtime_clock::time_point end_time_ = realtime_clock::max_time;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800658};
659
660} // namespace logger
661} // namespace aos
662
Austin Schuhb06f03b2021-02-17 22:00:37 -0800663#endif // AOS_EVENTS_LOGGING_LOG_READER_H_