blob: 0e346a0e526780cddf19637e8d7dbb1ac49c28ce [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
Austin Schuhaf8a0d32023-05-03 09:53:06 -07003#include <dirent.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08004#include <fcntl.h>
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08008
Tyler Chatowbf0609c2021-07-31 16:13:27 -07009#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -080010#include <vector>
11
Austin Schuh2f8fd752020-09-01 22:38:28 -070012#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080013#include "absl/types/span.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070014#include "flatbuffers/flatbuffers.h"
15#include "openssl/sha.h"
16
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070018#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070019#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080020#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080021#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070022#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080023#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080024#include "aos/network/remote_message_generated.h"
25#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080026#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080027#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070029#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070030#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080031
Austin Schuh15649d62019-12-28 16:36:38 -080032DEFINE_bool(skip_missing_forwarding_entries, false,
33 "If true, drop any forwarding entries with missing data. If "
34 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080035
Austin Schuh0ca1fd32020-12-18 22:53:05 -080036DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080037
Austin Schuh2f8fd752020-09-01 22:38:28 -070038DEFINE_bool(skip_order_validation, false,
39 "If true, ignore any out of orderness in replay");
40
Austin Schuhf0688662020-12-19 15:37:45 -080041DEFINE_double(
42 time_estimation_buffer_seconds, 2.0,
43 "The time to buffer ahead in the log file to accurately reconstruct time.");
44
Austin Schuhe33c08d2022-02-03 18:15:21 -080045DEFINE_string(
46 start_time, "",
47 "If set, start at this point in time in the log on the realtime clock.");
48DEFINE_string(
49 end_time, "",
50 "If set, end at this point in time in the log on the realtime clock.");
51
James Kuszmaul09632422022-05-25 15:56:19 -070052DEFINE_bool(drop_realtime_messages_before_start, false,
53 "If set, will drop any messages sent before the start of the "
54 "logfile in realtime replay. Setting this guarantees consistency "
55 "in timing with the original logfile, but means that you lose "
56 "access to fetched low-frequency messages.");
57
James Kuszmaula16a7912022-06-17 10:58:12 -070058DEFINE_double(
59 threaded_look_ahead_seconds, 2.0,
60 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
61 "Can validly be zero, but higher values are encouraged for realtime replay "
62 "in order to prevent the replay from ever having to block on waiting for "
63 "the reader to find the next message.");
64
Austin Schuhe309d2a2019-11-29 13:25:21 -080065namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070066namespace configuration {
67// We don't really want to expose this publicly, but log reader doesn't really
68// want to re-implement it.
69void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
70 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070071} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080072namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070073namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080074
Austin Schuh1c227352021-09-17 12:53:54 -070075bool CompareChannels(const Channel *c,
76 ::std::pair<std::string_view, std::string_view> p) {
77 int name_compare = c->name()->string_view().compare(p.first);
78 if (name_compare == 0) {
79 return c->type()->string_view() < p.second;
80 } else if (name_compare < 0) {
81 return true;
82 } else {
83 return false;
84 }
85}
86
87bool EqualsChannels(const Channel *c,
88 ::std::pair<std::string_view, std::string_view> p) {
89 return c->name()->string_view() == p.first &&
90 c->type()->string_view() == p.second;
91}
92
Austin Schuh0de30f32020-12-06 12:44:28 -080093// Copies the channel, removing the schema as we go. If new_name is provided,
94// it is used instead of the name inside the channel. If new_type is provided,
95// it is used instead of the type in the channel.
96flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
97 std::string_view new_name,
98 std::string_view new_type,
99 flatbuffers::FlatBufferBuilder *fbb) {
100 flatbuffers::Offset<flatbuffers::String> name_offset =
101 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
102 : new_name);
103 flatbuffers::Offset<flatbuffers::String> type_offset =
104 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
105 flatbuffers::Offset<flatbuffers::String> source_node_offset =
106 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
107 : 0;
108
109 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
110 destination_nodes_offset =
111 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
112
113 flatbuffers::Offset<
114 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
115 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
116
117 Channel::Builder channel_builder(*fbb);
118 channel_builder.add_name(name_offset);
119 channel_builder.add_type(type_offset);
120 if (c->has_frequency()) {
121 channel_builder.add_frequency(c->frequency());
122 }
123 if (c->has_max_size()) {
124 channel_builder.add_max_size(c->max_size());
125 }
126 if (c->has_num_senders()) {
127 channel_builder.add_num_senders(c->num_senders());
128 }
129 if (c->has_num_watchers()) {
130 channel_builder.add_num_watchers(c->num_watchers());
131 }
132 if (!source_node_offset.IsNull()) {
133 channel_builder.add_source_node(source_node_offset);
134 }
135 if (!destination_nodes_offset.IsNull()) {
136 channel_builder.add_destination_nodes(destination_nodes_offset);
137 }
138 if (c->has_logger()) {
139 channel_builder.add_logger(c->logger());
140 }
141 if (!logger_nodes_offset.IsNull()) {
142 channel_builder.add_logger_nodes(logger_nodes_offset);
143 }
144 if (c->has_read_method()) {
145 channel_builder.add_read_method(c->read_method());
146 }
147 if (c->has_num_readers()) {
148 channel_builder.add_num_readers(c->num_readers());
149 }
150 return channel_builder.Finish();
151}
152
Austin Schuhe309d2a2019-11-29 13:25:21 -0800153namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800154using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700155} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800156
Austin Schuhe33c08d2022-02-03 18:15:21 -0800157// Class to manage triggering events on the RT clock while replaying logs. Since
158// the RT clock can only change when we get a message, we only need to update
159// our timers when new messages are read.
160class EventNotifier {
161 public:
162 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
163 std::string_view name,
164 realtime_clock::time_point realtime_event_time)
165 : event_loop_(event_loop),
166 fn_(std::move(fn)),
167 realtime_event_time_(realtime_event_time) {
168 CHECK(event_loop_);
169 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
170
171 if (event_loop_->node() != nullptr) {
172 event_timer_->set_name(
173 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
174 } else {
175 event_timer_->set_name(name);
176 }
177 }
178
179 ~EventNotifier() { event_timer_->Disable(); }
180
James Kuszmaul09632422022-05-25 15:56:19 -0700181 // Sets the clock offset for realtime playback.
182 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
183 clock_offset_ = clock_offset;
184 }
185
Austin Schuhe33c08d2022-02-03 18:15:21 -0800186 // Returns the event trigger time.
187 realtime_clock::time_point realtime_event_time() const {
188 return realtime_event_time_;
189 }
190
191 // Observes the next message and potentially calls the callback or updates the
192 // timer.
193 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
194 realtime_clock::time_point realtime_message_time) {
195 if (realtime_message_time < realtime_event_time_) {
196 return;
197 }
198 if (called_) {
199 return;
200 }
201
202 // Move the callback wakeup time to the correct time (or make it now if
203 // there's a gap in time) now that we know it is before the next
204 // message.
205 const monotonic_clock::time_point candidate_monotonic =
206 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
207 const monotonic_clock::time_point monotonic_now =
208 event_loop_->monotonic_now();
209 if (candidate_monotonic < monotonic_now) {
210 // Whops, time went backwards. Just do it now.
211 HandleTime();
212 } else {
Philipp Schradera6712522023-07-05 20:25:11 -0700213 event_timer_->Schedule(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800214 }
215 }
216
217 private:
218 void HandleTime() {
219 if (!called_) {
220 called_ = true;
221 fn_();
222 }
223 }
224
225 EventLoop *event_loop_ = nullptr;
226 TimerHandler *event_timer_ = nullptr;
227 std::function<void()> fn_;
228
229 const realtime_clock::time_point realtime_event_time_ =
230 realtime_clock::min_time;
231
James Kuszmaul09632422022-05-25 15:56:19 -0700232 std::chrono::nanoseconds clock_offset_{0};
233
Austin Schuhe33c08d2022-02-03 18:15:21 -0800234 bool called_ = false;
235};
236
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800237LogReader::LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700238 const Configuration *replay_configuration,
239 const ReplayChannels *replay_channels)
240 : LogReader(SortParts({std::string(filename)}), replay_configuration,
241 replay_channels) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800242
Austin Schuh287d43d2020-12-04 20:19:33 -0800243LogReader::LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700244 const Configuration *replay_configuration,
245 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800246 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700247 replay_configuration_(replay_configuration),
248 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800249 SetStartTime(FLAGS_start_time);
250 SetEndTime(FLAGS_end_time);
251
Austin Schuh0ca51f32020-12-25 21:51:45 -0800252 CHECK_GT(log_files_.size(), 0u);
253 {
254 // Validate that we have the same config everwhere. This will be true if
255 // all the parts were sorted together and the configs match.
256 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800257 for (const LogFile &log_file : log_files_) {
258 if (log_file.config.get() == nullptr) {
259 LOG(FATAL) << "Couldn't find a config in " << log_file;
260 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800261 if (config == nullptr) {
262 config = log_file.config.get();
263 } else {
264 CHECK_EQ(config, log_file.config.get());
265 }
266 }
267 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800268
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700269 if (replay_channels_ != nullptr) {
270 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
271 "no messages will get replayed.";
272 }
273
Austin Schuh6331ef92020-01-07 18:28:09 -0800274 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800275
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700276 // Remap all existing remote timestamp channels. They will be recreated, and
277 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700278 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800279 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
280 "log_reader", node);
281
282 absl::btree_set<std::string_view> remote_nodes;
283
284 for (const Channel *channel : *logged_configuration()->channels()) {
285 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
286 continue;
287 }
288 if (!channel->has_destination_nodes()) {
289 continue;
290 }
291 for (const Connection *connection : *channel->destination_nodes()) {
292 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
293 node)) {
294 // Start by seeing if the split timestamp channels are being used for
295 // this message. If so, remap them.
296 const Channel *timestamp_channel = configuration::GetChannel(
297 logged_configuration(),
298 finder.SplitChannelName(channel, connection),
299 RemoteMessage::GetFullyQualifiedName(), "", node, true);
300
301 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700302 // If for some reason a timestamp channel is not NOT_LOGGED (which
303 // is unusual), then remap the channel so that the replayed channel
304 // doesn't overlap with the special separate replay we do for
305 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800306 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
307 RemapLoggedChannel<RemoteMessage>(
308 timestamp_channel->name()->string_view(), node);
309 }
310 continue;
311 }
312
313 // Otherwise collect this one up as a node to look for a combined
314 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700315 LOG(WARNING) << "Failed to find channel "
316 << finder.SplitChannelName(channel, connection)
317 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800318 remote_nodes.insert(connection->name()->string_view());
319 }
320 }
321 }
322
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700323 std::vector<const Node *> timestamp_logger_nodes =
324 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800325 for (const std::string_view remote_node : remote_nodes) {
326 const std::string channel = finder.CombinedChannelName(remote_node);
327
Austin Schuh0de30f32020-12-06 12:44:28 -0800328 // See if the log file is an old log with MessageHeader channels in it, or
329 // a newer log with RemoteMessage. If we find an older log, rename the
330 // type too along with the name.
331 if (HasChannel<MessageHeader>(channel, node)) {
332 CHECK(!HasChannel<RemoteMessage>(channel, node))
333 << ": Can't have both a MessageHeader and RemoteMessage remote "
334 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800335 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
336 // careful about updating the config, but there are fewer and fewer logs
337 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800338 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
339 "aos.message_bridge.RemoteMessage");
340 } else {
341 CHECK(HasChannel<RemoteMessage>(channel, node))
342 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
343 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
344 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800345 // Only bother to remap if there's something on the channel. We can
346 // tell if the channel was marked NOT_LOGGED or not. This makes the
347 // config not change un-necesarily when we replay a log with NOT_LOGGED
348 // messages.
349 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
350 RemapLoggedChannel<RemoteMessage>(channel, node);
351 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800352 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700353 }
354 }
355
Austin Schuh6aa77be2020-02-22 21:06:40 -0800356 if (replay_configuration) {
357 CHECK_EQ(configuration::MultiNode(configuration()),
358 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700359 << ": Log file and replay config need to both be multi or single "
360 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800361 }
362
Austin Schuh6f3babe2020-01-26 20:34:50 -0800363 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700364 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800365 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800366 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700367 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800368 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700369 << ": Log file and replay config need to have matching nodes "
370 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700371 for (const Node *node : *logged_configuration()->nodes()) {
372 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700373 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
374 << " in logged config that is not present in the replay "
375 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700376 }
377 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800378 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800379 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800380 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800381}
382
Austin Schuh6aa77be2020-02-22 21:06:40 -0800383LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700384 if (event_loop_factory_unique_ptr_) {
385 Deregister();
386 } else if (event_loop_factory_ != nullptr) {
387 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
388 "is destroyed";
389 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700390 // Zero out some buffers. It's easy to do use-after-frees on these, so make
391 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700392 if (remapped_configuration_buffer_) {
393 remapped_configuration_buffer_->Wipe();
394 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800395}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800396
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800397const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800398 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800399}
400
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800401const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800402 return remapped_configuration_;
403}
404
Austin Schuh07676622021-01-21 18:59:17 -0800405std::vector<const Node *> LogReader::LoggedNodes() const {
406 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800407}
Austin Schuh15649d62019-12-28 16:36:38 -0800408
Austin Schuh11d43732020-09-21 17:28:30 -0700409monotonic_clock::time_point LogReader::monotonic_start_time(
410 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800411 State *state =
412 states_[configuration::GetNodeIndex(configuration(), node)].get();
413 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
414
Austin Schuhf665eb42022-02-03 18:26:25 -0800415 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800416}
417
Austin Schuh11d43732020-09-21 17:28:30 -0700418realtime_clock::time_point LogReader::realtime_start_time(
419 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800420 State *state =
421 states_[configuration::GetNodeIndex(configuration(), node)].get();
422 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
423
Austin Schuhf665eb42022-02-03 18:26:25 -0800424 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800425}
426
Austin Schuh58646e22021-08-23 23:51:46 -0700427void LogReader::OnStart(std::function<void()> fn) {
428 CHECK(!configuration::MultiNode(configuration()));
429 OnStart(nullptr, std::move(fn));
430}
431
432void LogReader::OnStart(const Node *node, std::function<void()> fn) {
433 const int node_index = configuration::GetNodeIndex(configuration(), node);
434 CHECK_GE(node_index, 0);
435 CHECK_LT(node_index, static_cast<int>(states_.size()));
436 State *state = states_[node_index].get();
437 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
438
439 state->OnStart(std::move(fn));
440}
441
James Kuszmaula16a7912022-06-17 10:58:12 -0700442void LogReader::State::QueueThreadUntil(BootTimestamp time) {
443 if (threading_ == ThreadedBuffering::kYes) {
444 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
445 message_queuer_.emplace(
446 [this](const BootTimestamp queue_until) {
447 // This will be called whenever anything prompts us for any state
448 // change; there may be wakeups that result in us not having any new
449 // data to push (even if we aren't done), in which case we will return
450 // nullopt but not done().
451 if (last_queued_message_.has_value() &&
452 queue_until < last_queued_message_) {
453 return util::ThreadedQueue<TimestampedMessage,
454 BootTimestamp>::PushResult{
455 std::nullopt, false,
456 last_queued_message_ == BootTimestamp::max_time()};
457 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700458
James Kuszmaula16a7912022-06-17 10:58:12 -0700459 TimestampedMessage *message = timestamp_mapper_->Front();
460 // Upon reaching the end of the log, exit.
461 if (message == nullptr) {
462 last_queued_message_ = BootTimestamp::max_time();
463 return util::ThreadedQueue<TimestampedMessage,
464 BootTimestamp>::PushResult{std::nullopt,
465 false, true};
466 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700467
James Kuszmaula16a7912022-06-17 10:58:12 -0700468 last_queued_message_ = message->monotonic_event_time;
469 const util::ThreadedQueue<TimestampedMessage,
470 BootTimestamp>::PushResult result{
471 *message, queue_until >= last_queued_message_, false};
472 timestamp_mapper_->PopFront();
473 SeedSortedMessages();
474 return result;
475 },
476 time);
477 // Spin until the first few seconds of messages are queued up so that we
478 // don't end up with delays/inconsistent timing during the first few seconds
479 // of replay.
480 message_queuer_->WaitForNoMoreWork();
481 }
482}
483
Austin Schuh58646e22021-08-23 23:51:46 -0700484void LogReader::State::OnStart(std::function<void()> fn) {
485 on_starts_.emplace_back(std::move(fn));
486}
487
488void LogReader::State::RunOnStart() {
489 SetRealtimeOffset(monotonic_start_time(boot_count()),
490 realtime_start_time(boot_count()));
491
492 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
493 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800494 auto fn = [this]() {
495 for (size_t i = 0; i < on_starts_.size(); ++i) {
496 on_starts_[i]();
497 }
498 };
499 if (event_loop_factory_) {
500 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
501 } else {
502 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700503 }
504 stopped_ = false;
505 started_ = true;
506}
507
508void LogReader::OnEnd(std::function<void()> fn) {
509 CHECK(!configuration::MultiNode(configuration()));
510 OnEnd(nullptr, std::move(fn));
511}
512
513void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
514 const int node_index = configuration::GetNodeIndex(configuration(), node);
515 CHECK_GE(node_index, 0);
516 CHECK_LT(node_index, static_cast<int>(states_.size()));
517 State *state = states_[node_index].get();
518 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
519
520 state->OnEnd(std::move(fn));
521}
522
523void LogReader::State::OnEnd(std::function<void()> fn) {
524 on_ends_.emplace_back(std::move(fn));
525}
526
527void LogReader::State::RunOnEnd() {
528 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
529 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800530 auto fn = [this]() {
531 for (size_t i = 0; i < on_ends_.size(); ++i) {
532 on_ends_[i]();
533 }
534 };
535 if (event_loop_factory_) {
536 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
537 } else {
538 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700539 }
540
541 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800542 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700543 if (message_queuer_.has_value()) {
544 message_queuer_->StopPushing();
545 }
Austin Schuh58646e22021-08-23 23:51:46 -0700546}
547
James Kuszmaul94ca5132022-07-19 09:11:08 -0700548std::vector<
549 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
550LogReader::State::NonExclusiveChannels() {
551 CHECK_NOTNULL(node_event_loop_factory_);
552 const aos::Configuration *config = node_event_loop_factory_->configuration();
553 std::vector<
554 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
555 result{// Timing reports can be sent by logged and replayed applications.
556 {aos::configuration::GetChannel(config, "/aos",
557 "aos.timing.Report", "", node_),
558 NodeEventLoopFactory::ExclusiveSenders::kNo},
559 // AOS_LOG may be used in the log and in replay.
560 {aos::configuration::GetChannel(
561 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
562 NodeEventLoopFactory::ExclusiveSenders::kNo}};
563 for (const Node *const node : configuration::GetNodes(config)) {
564 if (node == nullptr) {
565 break;
566 }
567 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
568 config,
569 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700570 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700571 // The old-style remote timestamp channel can be populated from any
572 // channel, simulated or replayed.
573 if (old_timestamp_channel != nullptr) {
574 result.push_back(std::make_pair(
575 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
576 }
577 }
578 // Remove any channels that weren't found due to not existing in the
579 // config.
580 for (size_t ii = 0; ii < result.size();) {
581 if (result[ii].first == nullptr) {
582 result.erase(result.begin() + ii);
583 } else {
584 ++ii;
585 }
586 }
587 return result;
588}
589
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800590void LogReader::Register() {
591 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800592 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800593 Register(event_loop_factory_unique_ptr_.get());
594}
595
Austin Schuh58646e22021-08-23 23:51:46 -0700596void LogReader::RegisterWithoutStarting(
597 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800598 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700599 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800600 filters_ =
601 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800602 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700603 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800604 chrono::duration_cast<chrono::nanoseconds>(
605 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800606
Austin Schuhe639ea12021-01-25 13:00:22 -0800607 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700608 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800609 const size_t node_index =
610 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800611 std::vector<LogParts> filtered_parts = FilterPartsForNode(
612 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800613
James Kuszmaula16a7912022-06-17 10:58:12 -0700614 // We don't run with threading on the buffering for simulated event loops
615 // because we haven't attempted to validate how the interactions beteen the
616 // buffering and the timestamp mapper works when running multiple nodes
617 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800618 states_[node_index] = std::make_unique<State>(
619 filtered_parts.size() == 0u
620 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700621 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700622 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800623 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node));
Austin Schuh8bd96322020-02-13 21:18:22 -0800624 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700625 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800626 event_loop_factory_->GetNodeEventLoopFactory(node),
627 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700628
629 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800630 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800631 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800632 filters_->SetTimestampMappers(std::move(timestamp_mappers));
633
634 // Note: this needs to be set before any times are pulled, or we won't observe
635 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800636 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700637
Austin Schuh287d43d2020-12-04 20:19:33 -0800638 for (const Node *node : configuration::GetNodes(configuration())) {
639 const size_t node_index =
640 configuration::GetNodeIndex(configuration(), node);
641 State *state = states_[node_index].get();
642 for (const Node *other_node : configuration::GetNodes(configuration())) {
643 const size_t other_node_index =
644 configuration::GetNodeIndex(configuration(), other_node);
645 State *other_state = states_[other_node_index].get();
646 if (other_state != state) {
647 state->AddPeer(other_state);
648 }
649 }
650 }
651
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700652 // Register after making all the State objects so we can build references
653 // between them.
654 for (const Node *node : configuration::GetNodes(configuration())) {
655 const size_t node_index =
656 configuration::GetNodeIndex(configuration(), node);
657 State *state = states_[node_index].get();
658
Austin Schuh58646e22021-08-23 23:51:46 -0700659 // If we didn't find any log files with data in them, we won't ever get a
660 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700661 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700662 continue;
663 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700664
Austin Schuh58646e22021-08-23 23:51:46 -0700665 ++live_nodes_;
666
667 NodeEventLoopFactory *node_factory =
668 event_loop_factory_->GetNodeEventLoopFactory(node);
669 node_factory->OnStartup([this, state, node]() {
670 RegisterDuringStartup(state->MakeEventLoop(), node);
671 });
672 node_factory->OnShutdown([this, state, node]() {
673 RegisterDuringStartup(nullptr, node);
674 state->DestroyEventLoop();
675 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700676 }
677
James Kuszmaul46d82582020-05-09 19:50:09 -0700678 if (live_nodes_ == 0) {
679 LOG(FATAL)
680 << "Don't have logs from any of the nodes in the replay config--are "
681 "you sure that the replay config matches the original config?";
682 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800683
Austin Schuh87dd3832021-01-01 23:07:31 -0800684 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800685
Austin Schuh858c9f32020-08-31 16:56:12 -0700686 for (std::unique_ptr<State> &state : states_) {
687 state->SeedSortedMessages();
688 }
689
Austin Schuh6f3babe2020-01-26 20:34:50 -0800690 // Forwarding is tracked per channel. If it is enabled, we want to turn it
691 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700692 // nodes, and also replayed on the other nodes. This may not satisfy all
693 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800694 if (configuration::MultiNode(event_loop_factory_->configuration())) {
695 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
696 const Channel *channel = logged_configuration()->channels()->Get(i);
697 const Node *node = configuration::GetNode(
698 configuration(), channel->source_node()->string_view());
699
Austin Schuh8bd96322020-02-13 21:18:22 -0800700 State *state =
701 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800702
703 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700704 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800705
706 event_loop_factory_->DisableForwarding(remapped_channel);
707 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700708
709 // If we are replaying a log, we don't want a bunch of redundant messages
710 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700711 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800712 }
Austin Schuh891214d2021-11-11 20:35:02 -0800713
714 // Write pseudo start times out to file now that we are all setup.
715 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700716}
717
718void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
719 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800720 StartAfterRegister(event_loop_factory);
721}
722
723void LogReader::StartAfterRegister(
724 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700725 // We want to start the log file at the last start time of the log files
726 // from all the nodes. Compute how long each node's simulation needs to run
727 // to move time to this point.
728 distributed_clock::time_point start_time = distributed_clock::min_time;
729
730 // TODO(austin): We want an "OnStart" callback for each node rather than
731 // running until the last node.
732
733 for (std::unique_ptr<State> &state : states_) {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700734 CHECK(state);
Austin Schuh58646e22021-08-23 23:51:46 -0700735 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
736 << " for node " << MaybeNodeName(state->node()) << "now "
737 << state->monotonic_now();
738 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
739 continue;
740 }
741 // And start computing the start time on the distributed clock now that
742 // that works.
743 start_time = std::max(
744 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
745 }
746
747 // TODO(austin): If a node doesn't have a start time, we might not queue
748 // enough. If this happens, we'll explode with a frozen error eventually.
749
750 CHECK_GE(start_time, distributed_clock::epoch())
751 << ": Hmm, we have a node starting before the start of time. Offset "
752 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800753
Austin Schuhdda74ec2021-01-03 19:30:37 -0800754 {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800755 VLOG(1) << "Running until " << start_time << " in Register";
756 event_loop_factory_->RunFor(start_time.time_since_epoch());
757 VLOG(1) << "At start time";
Austin Schuhdda74ec2021-01-03 19:30:37 -0800758 }
Austin Schuh92547522019-12-28 14:33:43 -0800759
Austin Schuh8bd96322020-02-13 21:18:22 -0800760 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700761 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700762 if (state->realtime_start_time(0) != realtime_clock::min_time) {
763 state->SetRealtimeOffset(state->monotonic_start_time(0),
764 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700765 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700766 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
767 << " for node " << MaybeNodeName(state->event_loop()->node())
768 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700769 }
770
771 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800772 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800773 }
774}
775
Austin Schuh2f8fd752020-09-01 22:38:28 -0700776message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800777 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800778 if (filters_) {
779 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800780 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800781 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800782}
783
James Kuszmaul09632422022-05-25 15:56:19 -0700784// TODO(jkuszmaul): Make in-line modifications to
785// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
786// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800787void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700788 filters_ =
789 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
790 event_loop->configuration(), logged_configuration(),
791 log_files_[0].boots, FLAGS_skip_order_validation,
792 chrono::duration_cast<chrono::nanoseconds>(
793 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
794
795 std::vector<TimestampMapper *> timestamp_mappers;
796 for (const Node *node : configuration::GetNodes(configuration())) {
797 const size_t node_index =
798 configuration::GetNodeIndex(configuration(), node);
799 std::vector<LogParts> filtered_parts = FilterPartsForNode(
800 log_files_, node != nullptr ? node->name()->string_view() : "");
801
802 states_[node_index] = std::make_unique<State>(
803 filtered_parts.size() == 0u
804 ? nullptr
805 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700806 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800807 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node));
James Kuszmaul09632422022-05-25 15:56:19 -0700808 State *state = states_[node_index].get();
809
810 state->SetChannelCount(logged_configuration()->channels()->size());
811 timestamp_mappers.emplace_back(state->timestamp_mapper());
812 }
813
814 filters_->SetTimestampMappers(std::move(timestamp_mappers));
815
816 for (const Node *node : configuration::GetNodes(configuration())) {
817 const size_t node_index =
818 configuration::GetNodeIndex(configuration(), node);
819 State *state = states_[node_index].get();
820 for (const Node *other_node : configuration::GetNodes(configuration())) {
821 const size_t other_node_index =
822 configuration::GetNodeIndex(configuration(), other_node);
823 State *other_state = states_[other_node_index].get();
824 if (other_state != state) {
825 state->AddPeer(other_state);
826 }
827 }
828 }
829 for (const Node *node : configuration::GetNodes(configuration())) {
830 if (node == nullptr || node->name()->string_view() ==
831 event_loop->node()->name()->string_view()) {
832 Register(event_loop, event_loop->node());
833 } else {
834 Register(nullptr, node);
835 }
836 }
Austin Schuh58646e22021-08-23 23:51:46 -0700837}
838
839void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800840 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700841 states_[configuration::GetNodeIndex(configuration(), node)].get();
842
843 // If we didn't find any log files with data in them, we won't ever get a
844 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700845 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700846 return;
847 }
James Kuszmaul09632422022-05-25 15:56:19 -0700848
849 if (event_loop != nullptr) {
850 ++live_nodes_;
851 }
Austin Schuh58646e22021-08-23 23:51:46 -0700852
853 if (event_loop_factory_ != nullptr) {
854 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
855 [this, event_loop, node]() {
856 RegisterDuringStartup(event_loop, node);
857 });
858 } else {
859 RegisterDuringStartup(event_loop, node);
860 }
861}
862
863void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700864 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700865 CHECK(event_loop->configuration() == configuration());
866 }
867
868 State *state =
869 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800870
James Kuszmaul09632422022-05-25 15:56:19 -0700871 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800872 state->ClearTimeFlags();
873 }
874
Austin Schuh858c9f32020-08-31 16:56:12 -0700875 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800876
Tyler Chatow67ddb032020-01-12 14:30:04 -0800877 // We don't run timing reports when trying to print out logged data, because
878 // otherwise we would end up printing out the timing reports themselves...
879 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700880 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700881 event_loop->SkipTimingReport();
882 event_loop->SkipAosLog();
883 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800884
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700885 for (size_t logged_channel_index = 0;
886 logged_channel_index < logged_configuration()->channels()->size();
887 ++logged_channel_index) {
888 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700889 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700890 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800891
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700892 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700893 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700894
895 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700896
Austin Schuh58646e22021-08-23 23:51:46 -0700897 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
898 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700899 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700900 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800901
Austin Schuh58646e22021-08-23 23:51:46 -0700902 // We've got a message which is being forwarded to this node.
903 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700904
905 source_state =
906 states_[configuration::GetNodeIndex(configuration(), source_node)]
907 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800908 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700909
Austin Schuh58646e22021-08-23 23:51:46 -0700910 // We are the source, and it is forwarded.
911 const bool is_forwarded =
912 configuration::ChannelIsSendableOnNode(channel, node) &&
913 configuration::ConnectionCount(channel);
914
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700915 state->SetChannel(
916 logged_channel_index,
917 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700918 event_loop && logged &&
919 configuration::ChannelIsReadableOnNode(channel, node)
920 ? event_loop->MakeRawSender(channel)
921 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700922 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700923
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700924 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700925 const Node *source_node = configuration::GetNode(
926 configuration(), channel->source_node()->string_view());
927
928 for (const Connection *connection : *channel->destination_nodes()) {
929 const bool delivery_time_is_logged =
930 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
931 source_node);
932
933 if (delivery_time_is_logged) {
934 State *destination_state =
935 states_[configuration::GetNodeIndex(
936 configuration(), connection->name()->string_view())]
937 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700938 if (destination_state) {
939 destination_state->SetRemoteTimestampSender(
940 logged_channel_index,
941 event_loop ? state->RemoteTimestampSender(channel, connection)
942 : nullptr);
943 }
Austin Schuh58646e22021-08-23 23:51:46 -0700944 }
945 }
946 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800947 }
948
Austin Schuh58646e22021-08-23 23:51:46 -0700949 if (!event_loop) {
950 state->ClearRemoteTimestampSenders();
951 state->set_timer_handler(nullptr);
952 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800953 return;
954 }
955
Austin Schuh858c9f32020-08-31 16:56:12 -0700956 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700957 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800958 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700959 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700960 if (exit_on_finish_ && live_nodes_ == 0 &&
961 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700962 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800963 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800964 return;
965 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700966
Austin Schuhdda74ec2021-01-03 19:30:37 -0800967 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700968
969 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
970 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800971
Austin Schuhe309d2a2019-11-29 13:25:21 -0800972 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700973 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700974 if (event_loop_factory_ != nullptr) {
975 // Only enforce exact timing in simulation.
976 if (!FLAGS_skip_order_validation) {
977 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
978 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
979 << monotonic_now << " trying to send "
980 << timestamped_message.monotonic_event_time << " failure "
981 << state->DebugString();
982 } else if (BootTimestamp{.boot = state->boot_count(),
983 .time = monotonic_now} !=
984 timestamped_message.monotonic_event_time) {
985 LOG(WARNING) << "Check failed: monotonic_now == "
986 "timestamped_message.monotonic_event_time) ("
987 << monotonic_now << " vs. "
988 << timestamped_message.monotonic_event_time
989 << "): " << FlatbufferToJson(state->event_loop()->node())
990 << " Now " << monotonic_now << " trying to send "
991 << timestamped_message.monotonic_event_time << " failure "
992 << state->DebugString();
993 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700994 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800995
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700996 if (timestamped_message.monotonic_event_time.time >
997 state->monotonic_start_time(
998 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700999 event_loop_factory_ != nullptr ||
1000 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001001 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001002 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001003 BootTimestamp::min_time() &&
1004 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001005 // Confirm that the message was sent on the sending node before the
1006 // destination node (this node). As a proxy, do this by making sure
1007 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001008 //
1009 // TODO(austin): <= means that the cause message (which we know) could
1010 // happen after the effect even though we know they are at the same
1011 // time. I doubt anyone will notice for a bit, but we should really
1012 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001013 BootTimestamp monotonic_remote_now =
1014 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001015 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001016 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001017 monotonic_remote_now.boot)
1018 << state->event_loop()->node()->name()->string_view() << " to "
1019 << state->remote_node(timestamped_message.channel_index)
1020 ->name()
1021 ->string_view()
1022 << " while trying to send a message on "
1023 << configuration::CleanedChannelToString(
1024 logged_configuration()->channels()->Get(
1025 timestamped_message.channel_index))
1026 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001027 CHECK_LE(timestamped_message.monotonic_remote_time,
1028 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001029 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001030 << state->remote_node(timestamped_message.channel_index)
1031 ->name()
1032 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001033 << " while trying to send a message on "
1034 << configuration::CleanedChannelToString(
1035 logged_configuration()->channels()->Get(
1036 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001037 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001038 } else if (monotonic_remote_now.boot !=
1039 timestamped_message.monotonic_remote_time.boot) {
1040 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1041 << " vs "
1042 << timestamped_message.monotonic_remote_time.boot;
1043 } else if (timestamped_message.monotonic_remote_time >
1044 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001045 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001046 << "Check failed: timestamped_message.monotonic_remote_time < "
1047 "state->monotonic_remote_now(timestamped_message.channel_"
1048 "index) ("
1049 << timestamped_message.monotonic_remote_time << " vs. "
1050 << state->monotonic_remote_now(
1051 timestamped_message.channel_index)
1052 << ") " << state->event_loop()->node()->name()->string_view()
1053 << " to "
1054 << state->remote_node(timestamped_message.channel_index)
1055 ->name()
1056 ->string_view()
1057 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001058 << " ("
1059 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001060 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001061 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001062 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001063 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001064 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001065 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001066 << ") " << state->DebugString();
1067 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001068 }
1069
Austin Schuh15649d62019-12-28 16:36:38 -08001070 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001071 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001072 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001073
Austin Schuh2f8fd752020-09-01 22:38:28 -07001074 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001075 << timestamped_message.monotonic_event_time << " "
1076 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001077 // TODO(austin): std::move channel_data in and make that efficient in
1078 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001079 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001080 } else if (state->found_last_message() ||
1081 (!ignore_missing_data_ &&
1082 // When starting up, we can have data which was sent before
1083 // the log starts, but the timestamp was after the log
1084 // starts. This is unreasonable to avoid, so ignore the
1085 // missing data.
1086 timestamped_message.monotonic_remote_time.time >=
1087 state->monotonic_remote_start_time(
1088 timestamped_message.monotonic_remote_time.boot,
1089 timestamped_message.channel_index) &&
1090 !FLAGS_skip_missing_forwarding_entries)) {
1091 if (!state->found_last_message()) {
1092 // We've found a timestamp without data that we expect to have data
1093 // for. This likely means that we are at the end of the log file.
1094 // Record it and CHECK that in the rest of the log file, we don't find
1095 // any more data on that channel. Not all channels will end at the
1096 // same point in time since they can be in different files.
1097 VLOG(1) << "Found the last message on channel "
1098 << timestamped_message.channel_index << ", "
1099 << configuration::CleanedChannelToString(
1100 logged_configuration()->channels()->Get(
1101 timestamped_message.channel_index))
1102 << " on node " << MaybeNodeName(state->event_loop()->node())
1103 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001104
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001105 // The user might be working with log files from 1 node but forgot to
1106 // configure the infrastructure to log data for a remote channel on
1107 // that node. That can be very hard to debug, even though the log
1108 // reader is doing the right thing. At least log a warning in that
1109 // case and tell the user what is happening so they can either update
1110 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001111 const std::vector<std::string> logger_nodes =
1112 FindLoggerNodes(log_files_);
1113 if (logger_nodes.size()) {
1114 // We have old logs which don't have the logger nodes logged. In
1115 // that case, we can't be helpful :(
1116 bool data_logged = false;
1117 const Channel *channel = logged_configuration()->channels()->Get(
1118 timestamped_message.channel_index);
1119 for (const std::string &node : logger_nodes) {
1120 data_logged |=
1121 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1122 }
1123 if (!data_logged) {
1124 LOG(WARNING) << "Got a timestamp without any logfiles which "
1125 "could contain data for channel "
1126 << configuration::CleanedChannelToString(channel);
1127 LOG(WARNING) << "Only have logs logged on ["
1128 << absl::StrJoin(logger_nodes, ", ") << "]";
1129 LOG(WARNING)
1130 << "Dropping the rest of the data on "
1131 << state->event_loop()->node()->name()->string_view();
1132 LOG(WARNING)
1133 << "Consider using --skip_missing_forwarding_entries to "
1134 "bypass this, update your config to log it, or add data "
1135 "from one of the nodes it is logged on.";
1136 }
1137 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001138 // Now that we found the end of one channel, artificially stop the
1139 // rest by setting the found_last_message bit. It is confusing when
1140 // part of your data gets replayed but not all. The rest of them will
1141 // get dropped as they are replayed to keep memory usage down.
1142 state->SetFoundLastMessage(true);
1143
1144 // Vector storing if we've seen a nullptr message or not per channel.
1145 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001146 }
1147
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001148 // Make sure that once we have seen the last message on a channel,
1149 // data doesn't start back up again. If the user wants to play
1150 // through events like this, they can set
1151 // --skip_missing_forwarding_entries or ignore_missing_data_.
1152 if (timestamped_message.data == nullptr) {
1153 state->set_last_message(timestamped_message.channel_index);
1154 } else {
1155 if (state->last_message(timestamped_message.channel_index)) {
1156 LOG(FATAL) << "Found missing data in the middle of the log file on "
1157 "channel "
1158 << timestamped_message.channel_index << " "
1159 << configuration::StrippedChannelToString(
1160 logged_configuration()->channels()->Get(
1161 timestamped_message.channel_index))
1162 << " " << timestamped_message << " "
1163 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001164 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001165 }
Austin Schuh92547522019-12-28 14:33:43 -08001166 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001167 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001168 LOG(WARNING)
1169 << "Not sending data from before the start of the log file. "
1170 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1171 .count()
1172 << " start "
1173 << monotonic_start_time(state->node()).time_since_epoch().count()
1174 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001175 }
1176
James Kuszmaula16a7912022-06-17 10:58:12 -07001177 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001178 if (next_time != BootTimestamp::max_time()) {
1179 if (next_time.boot != state->boot_count()) {
1180 VLOG(1) << "Next message for "
1181 << MaybeNodeName(state->event_loop()->node())
1182 << "is on the next boot, " << next_time << " now is "
1183 << state->monotonic_now();
1184 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001185 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001186 return;
1187 }
James Kuszmaul09632422022-05-25 15:56:19 -07001188 if (event_loop_factory_ != nullptr) {
1189 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1190 << "wakeup for " << next_time.time << "("
1191 << state->ToDistributedClock(next_time.time)
1192 << " distributed), now is " << state->monotonic_now();
1193 } else {
1194 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1195 << "wakeup for " << next_time.time << ", now is "
1196 << state->monotonic_now();
1197 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001198 // TODO(james): This can result in negative times getting passed-through
1199 // in realtime replay.
Philipp Schradera6712522023-07-05 20:25:11 -07001200 state->Schedule(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001201 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001202 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1203 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001204 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001206 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001207 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001208 // Doesn't apply to single-EventLoop replay since the watchers in question
1209 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001210 if (event_loop_factory_ != nullptr) {
Philipp Schradera6712522023-07-05 20:25:11 -07001211 state->Schedule(monotonic_now + event_loop_factory_->send_delay() +
1212 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001213 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001214 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001215
Austin Schuh2f8fd752020-09-01 22:38:28 -07001216 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1217 << state->event_loop()->context().monotonic_event_time << " now "
1218 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001219 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001220
James Kuszmaula16a7912022-06-17 10:58:12 -07001221 state->SeedSortedMessages();
1222
1223 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001224 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001225 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1226 if (start_time_ != realtime_clock::min_time) {
1227 state->SetStartTimeFlag(start_time_);
1228 }
1229 if (end_time_ != realtime_clock::max_time) {
1230 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001231 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001232 }
Austin Schuh58646e22021-08-23 23:51:46 -07001233 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001234 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001235 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001236 // Queue up messages and then set clock offsets (we don't want to set
1237 // clock offsets before we've done the work of getting the first messages
1238 // primed).
1239 state->QueueThreadUntil(
1240 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1241 std::chrono::duration<double>(
1242 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001243 state->MaybeSetClockOffset();
Philipp Schradera6712522023-07-05 20:25:11 -07001244 state->Schedule(next_time.time);
1245 state->SetUpStartupTimer();
Austin Schuh58646e22021-08-23 23:51:46 -07001246 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001247 }
1248}
1249
Austin Schuhe33c08d2022-02-03 18:15:21 -08001250void LogReader::SetEndTime(std::string end_time) {
1251 if (end_time.empty()) {
1252 SetEndTime(realtime_clock::max_time);
1253 } else {
1254 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1255 aos::realtime_clock::FromString(end_time);
1256 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1257 << "'. Expected a date in the format of "
1258 "2021-01-15_15-30-35.000000000.";
1259 SetEndTime(*parsed_end_time);
1260 }
1261}
1262
1263void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1264 end_time_ = end_time;
1265}
1266
1267void LogReader::SetStartTime(std::string start_time) {
1268 if (start_time.empty()) {
1269 SetStartTime(realtime_clock::min_time);
1270 } else {
1271 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1272 aos::realtime_clock::FromString(start_time);
1273 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1274 << "'. Expected a date in the format of "
1275 "2021-01-15_15-30-35.000000000.";
1276 SetStartTime(*parsed_start_time);
1277 }
1278}
1279
1280void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1281 start_time_ = start_time;
1282}
1283
Austin Schuhe309d2a2019-11-29 13:25:21 -08001284void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001285 // Make sure that things get destroyed in the correct order, rather than
1286 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001287 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001288 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001289 }
Austin Schuh92547522019-12-28 14:33:43 -08001290
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001291 event_loop_factory_unique_ptr_.reset();
1292 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001293}
1294
James Kuszmaul53da7f32022-09-11 11:11:55 -07001295namespace {
1296// Checks if the specified channel name/type exists in the config and, depending
1297// on the value of conflict_handling, calls conflict_handler or just dies.
1298template <typename F>
1299void CheckAndHandleRemapConflict(std::string_view new_name,
1300 std::string_view new_type,
1301 const Configuration *config,
1302 LogReader::RemapConflict conflict_handling,
1303 F conflict_handler) {
1304 const Channel *existing_channel =
1305 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1306 if (existing_channel != nullptr) {
1307 switch (conflict_handling) {
1308 case LogReader::RemapConflict::kDisallow:
1309 LOG(FATAL)
1310 << "Channel "
1311 << configuration::StrippedChannelToString(existing_channel)
1312 << " is already used--you can't remap a logged channel to it.";
1313 break;
1314 case LogReader::RemapConflict::kCascade:
1315 LOG(INFO) << "Automatically remapping "
1316 << configuration::StrippedChannelToString(existing_channel)
1317 << " to avoid conflicts.";
1318 conflict_handler();
1319 break;
1320 }
1321 }
1322}
1323} // namespace
1324
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001325void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001326 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001327 std::string_view new_type,
1328 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001329 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1330 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001331}
1332
Austin Schuh01b4c352020-09-21 23:09:39 -07001333void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1334 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001335 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001336 std::string_view new_type,
1337 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001338 if (node != nullptr) {
1339 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1340 }
1341 if (replay_channels_ != nullptr) {
1342 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1343 std::make_pair(std::string{name}, std::string{type})) !=
1344 replay_channels_->end())
1345 << "Attempted to remap channel " << name << " " << type
1346 << " which is not included in the replay channels passed to LogReader.";
1347 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001348 const Channel *remapped_channel =
1349 configuration::GetChannel(logged_configuration(), name, type, "", node);
1350 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1351 << "\", \"type\": \"" << type << "\"}";
1352 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1353 << "\"}";
1354 VLOG(1) << "Remapped "
1355 << aos::configuration::StrippedChannelToString(remapped_channel);
1356
1357 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1358 // we want it to degrade if the heuristics fail to just work.
1359 //
1360 // The easiest way to do this is going to be incredibly specific and verbose.
1361 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1362 // /original/0/spray. Then, create a map from /original/spray to
1363 // /original/0/spray for just the type we were asked for.
1364 if (name != remapped_channel->name()->string_view()) {
1365 MapT new_map;
1366 new_map.match = std::make_unique<ChannelT>();
1367 new_map.match->name = absl::StrCat(add_prefix, name);
1368 new_map.match->type = type;
1369 if (node != nullptr) {
1370 new_map.match->source_node = node->name()->str();
1371 }
1372 new_map.rename = std::make_unique<ChannelT>();
1373 new_map.rename->name =
1374 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1375 maps_.emplace_back(std::move(new_map));
1376 }
1377
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001378 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001379 const size_t channel_index =
1380 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1381 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1382 << "Already remapped channel "
1383 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001384
1385 RemappedChannel remapped_channel_struct;
1386 remapped_channel_struct.remapped_name =
1387 std::string(add_prefix) +
1388 std::string(remapped_channel->name()->string_view());
1389 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001390 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1391 CheckAndHandleRemapConflict(
1392 remapped_channel_struct.remapped_name, remapped_type,
1393 remapped_configuration_, conflict_handling,
1394 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1395 conflict_handling]() {
1396 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1397 node, add_prefix, "", conflict_handling);
1398 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001399 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001400 MakeRemappedConfig();
1401}
1402
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001403void LogReader::RenameLoggedChannel(const std::string_view name,
1404 const std::string_view type,
1405 const std::string_view new_name,
1406 const std::vector<MapT> &add_maps) {
1407 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1408}
1409
1410void LogReader::RenameLoggedChannel(const std::string_view name,
1411 const std::string_view type,
1412 const Node *const node,
1413 const std::string_view new_name,
1414 const std::vector<MapT> &add_maps) {
1415 if (node != nullptr) {
1416 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1417 }
1418 // First find the channel and rename it.
1419 const Channel *remapped_channel =
1420 configuration::GetChannel(logged_configuration(), name, type, "", node);
1421 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1422 << "\", \"type\": \"" << type << "\"}";
1423 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1424 << "\"}";
1425 VLOG(1) << "Remapped "
1426 << aos::configuration::StrippedChannelToString(remapped_channel);
1427
1428 const size_t channel_index =
1429 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1430 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1431 << "Already remapped channel "
1432 << configuration::CleanedChannelToString(remapped_channel);
1433
1434 RemappedChannel remapped_channel_struct;
1435 remapped_channel_struct.remapped_name = new_name;
1436 remapped_channel_struct.new_type.clear();
1437 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1438
1439 // Then add any provided maps.
1440 for (const MapT &map : add_maps) {
1441 maps_.push_back(map);
1442 }
1443
1444 // Finally rewrite the config.
1445 MakeRemappedConfig();
1446}
1447
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001448void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001449 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001450 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001451 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001452 << ": Can't change the mapping after the events are scheduled.";
1453 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001454 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001455
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001456 // If no remapping occurred and we are using the original config, then there
1457 // is nothing interesting to do here.
1458 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001459 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001460 return;
1461 }
1462 // Config to copy Channel definitions from. Use the specified
1463 // replay_configuration_ if it has been provided.
1464 const Configuration *const base_config = replay_configuration_ == nullptr
1465 ? logged_configuration()
1466 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001467
1468 // Create a config with all the channels, but un-sorted/merged. Collect up
1469 // the schemas while we do this. Call MergeConfiguration to sort everything,
1470 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001471
1472 // This is the builder that we use for the config containing all the new
1473 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001474 flatbuffers::FlatBufferBuilder fbb;
1475 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001476 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001477
1478 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1479 << ": Merging logic needs to be updated when the number of channel "
1480 "fields changes.";
1481
1482 // List of schemas.
1483 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1484 // Make sure our new RemoteMessage schema is in there for old logs without it.
1485 schema_map.insert(std::make_pair(
1486 RemoteMessage::GetFullyQualifiedName(),
1487 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1488 message_bridge::RemoteMessageSchema()))));
1489
1490 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001491 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001492 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001493 base_config, logged_configuration()->channels()->Get(pair.first), "",
1494 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001495 channel_offsets.emplace_back(
1496 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001497
1498 if (c->has_destination_nodes()) {
1499 for (const Connection *connection : *c->destination_nodes()) {
1500 switch (connection->timestamp_logger()) {
1501 case LoggerConfig::LOCAL_LOGGER:
1502 case LoggerConfig::NOT_LOGGED:
1503 // There is no timestamp channel associated with this, so ignore it.
1504 break;
1505
1506 case LoggerConfig::REMOTE_LOGGER:
1507 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1508 // We want to make a split timestamp channel regardless of what type
1509 // of log this used to be. No sense propagating the single
1510 // timestamp channel.
1511
1512 CHECK(connection->has_timestamp_logger_nodes());
1513 for (const flatbuffers::String *timestamp_logger_node :
1514 *connection->timestamp_logger_nodes()) {
1515 const Node *node = configuration::GetNode(
1516 logged_configuration(), timestamp_logger_node->string_view());
1517 message_bridge::ChannelTimestampFinder finder(
1518 logged_configuration(), "log_reader", node);
1519
1520 // We are assuming here that all the maps are setup correctly to
1521 // handle arbitrary timestamps. Apply the maps for this node to
1522 // see what name this ends up with.
1523 std::string name = finder.SplitChannelName(
1524 pair.second.remapped_name, c->type()->str(), connection);
1525 std::string unmapped_name = name;
1526 configuration::HandleMaps(logged_configuration()->maps(), &name,
1527 "aos.message_bridge.RemoteMessage",
1528 node);
1529 CHECK_NE(name, unmapped_name)
1530 << ": Remote timestamp channel was not remapped, this is "
1531 "very fishy";
1532 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1533 fbb.CreateString(name);
1534 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1535 fbb.CreateString("aos.message_bridge.RemoteMessage");
1536 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1537 fbb.CreateString(timestamp_logger_node->string_view());
1538
1539 // Now, build a channel. Don't log it, 2 senders, and match the
1540 // source frequency.
1541 Channel::Builder channel_builder(fbb);
1542 channel_builder.add_name(channel_name_offset);
1543 channel_builder.add_type(channel_type_offset);
1544 channel_builder.add_source_node(source_node_offset);
1545 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1546 channel_builder.add_num_senders(2);
1547 if (c->has_frequency()) {
1548 channel_builder.add_frequency(c->frequency());
1549 }
1550 channel_offsets.emplace_back(channel_builder.Finish());
1551 }
1552 break;
1553 }
1554 }
1555 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001556 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001557
Austin Schuh0de30f32020-12-06 12:44:28 -08001558 // Now reconstruct the original channels, translating types as needed
1559 for (const Channel *c : *base_config->channels()) {
1560 // Search for a mapping channel.
1561 std::string_view new_type = "";
1562 for (auto &pair : remapped_channels_) {
1563 const Channel *const remapped_channel =
1564 logged_configuration()->channels()->Get(pair.first);
1565 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1566 remapped_channel->type()->string_view() == c->type()->string_view()) {
1567 new_type = pair.second.new_type;
1568 break;
1569 }
1570 }
1571
1572 // Copy everything over.
1573 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1574
1575 // Add the schema if it doesn't exist.
1576 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1577 CHECK(c->has_schema());
1578 schema_map.insert(std::make_pair(c->type()->string_view(),
1579 RecursiveCopyFlatBuffer(c->schema())));
1580 }
1581 }
1582
1583 // The MergeConfiguration API takes a vector, not a map. Convert.
1584 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1585 while (!schema_map.empty()) {
1586 schemas.emplace_back(std::move(schema_map.begin()->second));
1587 schema_map.erase(schema_map.begin());
1588 }
1589
1590 // Create the Configuration containing the new channels that we want to add.
1591 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1592 channels_offset =
1593 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1594
1595 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001596 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001597 if (base_config->maps()) {
1598 for (const Map *map : *base_config->maps()) {
1599 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1600 }
1601 }
1602
1603 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001604 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001605 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001606 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001607 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001608 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1609 if (!map.match->type.empty()) {
1610 match_type_offset = fbb.CreateString(map.match->type);
1611 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001612 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1613 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001614 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001615 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001616 CHECK(!map.rename->name.empty());
1617 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1618 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001619 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001620 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001621 if (!match_type_offset.IsNull()) {
1622 match_builder.add_type(match_type_offset);
1623 }
1624 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001625 match_builder.add_source_node(match_source_node_offset);
1626 }
1627 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1628
Austin Schuh0de30f32020-12-06 12:44:28 -08001629 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001630 rename_builder.add_name(rename_name_offset);
1631 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1632
Austin Schuh0de30f32020-12-06 12:44:28 -08001633 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001634 map_builder.add_match(match_offset);
1635 map_builder.add_rename(rename_offset);
1636 map_offsets.emplace_back(map_builder.Finish());
1637 }
1638
Austin Schuh0de30f32020-12-06 12:44:28 -08001639 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1640 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001641
Austin Schuh0de30f32020-12-06 12:44:28 -08001642 // And copy everything else over.
1643 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1644 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1645
1646 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1647 applications_offset =
1648 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1649
1650 // Now insert everything else in unmodified.
1651 ConfigurationBuilder configuration_builder(fbb);
1652 if (!channels_offset.IsNull()) {
1653 configuration_builder.add_channels(channels_offset);
1654 }
1655 if (!maps_offsets.IsNull()) {
1656 configuration_builder.add_maps(maps_offsets);
1657 }
1658 if (!nodes_offset.IsNull()) {
1659 configuration_builder.add_nodes(nodes_offset);
1660 }
1661 if (!applications_offset.IsNull()) {
1662 configuration_builder.add_applications(applications_offset);
1663 }
1664
1665 if (base_config->has_channel_storage_duration()) {
1666 configuration_builder.add_channel_storage_duration(
1667 base_config->channel_storage_duration());
1668 }
1669
1670 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1671 << ": Merging logic needs to be updated when the number of configuration "
1672 "fields changes.";
1673
1674 fbb.Finish(configuration_builder.Finish());
1675
1676 // Clean it up and return it! By using MergeConfiguration here, we'll
1677 // actually get a deduplicated config for free too.
1678 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1679 configuration::MergeConfiguration(
1680 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1681
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001682 remapped_configuration_buffer_ =
1683 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001684 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001685
1686 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001687
1688 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001689}
1690
Naman Guptacf6d4422023-03-01 11:41:00 -08001691std::unique_ptr<const ReplayChannelIndices>
1692LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001693 if (replay_channels_ == nullptr) {
1694 return nullptr;
1695 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001696 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1697 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001698 for (auto const &channel : *replay_channels_) {
1699 const Channel *ch = configuration::GetChannel(
1700 logged_configuration(), channel.first, channel.second, "", node);
1701 if (ch == nullptr) {
1702 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1703 << " not found in configuration for node: "
1704 << node->name()->string_view() << " Skipping ...";
1705 continue;
1706 }
1707 const size_t channel_index =
1708 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001709 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001710 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001711 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1712 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001713 }
1714}
1715
Austin Schuh1c227352021-09-17 12:53:54 -07001716std::vector<const Channel *> LogReader::RemappedChannels() const {
1717 std::vector<const Channel *> result;
1718 result.reserve(remapped_channels_.size());
1719 for (auto &pair : remapped_channels_) {
1720 const Channel *const logged_channel =
1721 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1722
1723 auto channel_iterator = std::lower_bound(
1724 remapped_configuration_->channels()->cbegin(),
1725 remapped_configuration_->channels()->cend(),
1726 std::make_pair(std::string_view(pair.second.remapped_name),
1727 logged_channel->type()->string_view()),
1728 CompareChannels);
1729
1730 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1731 CHECK(EqualsChannels(
1732 *channel_iterator,
1733 std::make_pair(std::string_view(pair.second.remapped_name),
1734 logged_channel->type()->string_view())));
1735 result.push_back(*channel_iterator);
1736 }
1737 return result;
1738}
1739
Austin Schuh6f3babe2020-01-26 20:34:50 -08001740const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001741 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001742 const Channel *channel) {
1743 std::string_view channel_name = channel->name()->string_view();
1744 std::string_view channel_type = channel->type()->string_view();
1745 const int channel_index =
1746 configuration::ChannelIndex(logged_configuration(), channel);
1747 // If the channel is remapped, find the correct channel name to use.
1748 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001749 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001750 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001751 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001752 }
1753
Austin Schuhee711052020-08-24 16:06:09 -07001754 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001755 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001756 configuration(), channel_name, channel_type,
1757 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001758
1759 CHECK(remapped_channel != nullptr)
1760 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1761 << channel_type << "\"} because it is not in the provided configuration.";
1762
1763 return remapped_channel;
1764}
1765
James Kuszmaul09632422022-05-25 15:56:19 -07001766LogReader::State::State(
1767 std::unique_ptr<TimestampMapper> timestamp_mapper,
1768 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001769 std::function<void()> notice_realtime_end, const Node *node,
1770 LogReader::State::ThreadedBuffering threading,
Naman Guptacf6d4422023-03-01 11:41:00 -08001771 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices)
James Kuszmaul09632422022-05-25 15:56:19 -07001772 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001773 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001774 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001775 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001776 threading_(threading),
Naman Guptacf6d4422023-03-01 11:41:00 -08001777 replay_channel_indices_(std::move(replay_channel_indices)) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001778 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1779 // with this node. If there are no log parts for the node, there will be no
1780 // log data, and so we do not need to worry about the replay channel filters.
1781 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001782 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001783 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001784 const TimestampedMessage &message) -> bool {
1785 auto const begin = filter->cbegin();
1786 auto const end = filter->cend();
1787 // TODO: benchmark strategies for channel_index matching
1788 return std::binary_search(begin, end, message.channel_index);
1789 });
1790 }
1791}
Austin Schuh287d43d2020-12-04 20:19:33 -08001792
1793void LogReader::State::AddPeer(State *peer) {
1794 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1795 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1796 }
1797}
Austin Schuh858c9f32020-08-31 16:56:12 -07001798
Austin Schuh58646e22021-08-23 23:51:46 -07001799void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001800 NodeEventLoopFactory *node_event_loop_factory,
1801 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001802 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001803 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001804}
1805
1806void LogReader::State::SetChannelCount(size_t count) {
1807 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001808 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001809 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001810 channel_source_state_.resize(count);
1811 factory_channel_index_.resize(count);
1812 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001813}
1814
Austin Schuh58646e22021-08-23 23:51:46 -07001815void LogReader::State::SetRemoteTimestampSender(
1816 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1817 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1818}
1819
Austin Schuh858c9f32020-08-31 16:56:12 -07001820void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001821 size_t logged_channel_index, size_t factory_channel_index,
1822 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001823 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1824 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001825 channels_[logged_channel_index] = std::move(sender);
1826 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001827 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001828
Austin Schuh58646e22021-08-23 23:51:46 -07001829 if (is_forwarded) {
1830 queue_index_map_[logged_channel_index] =
1831 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001832 }
1833
1834 factory_channel_index_[logged_channel_index] = factory_channel_index;
1835}
1836
James Kuszmaula16a7912022-06-17 10:58:12 -07001837void LogReader::State::TrackMessageSendTiming(
1838 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1839 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1840 return;
1841 }
1842
1843 timing::MessageTimingT sample;
1844 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1845 sender.channel());
1846 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1847 sample.actual_send_time =
1848 sender.monotonic_sent_time().time_since_epoch().count();
1849 sample.send_time_error = aos::time::DurationInSeconds(
1850 expected_send_time - sender.monotonic_sent_time());
1851 send_timings_.push_back(sample);
1852
1853 // Somewhat arbitrarily send out timing information in batches of 100. No need
1854 // to create excessive overhead in regenerated logfiles.
1855 // TODO(james): The overhead may be fine.
1856 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1857 CHECK(timing_statistics_sender_.valid());
1858 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1859 SendMessageTimings();
1860 }
1861}
1862
1863void LogReader::State::SendMessageTimings() {
1864 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1865 return;
1866 }
1867 auto builder = timing_statistics_sender_.MakeBuilder();
1868 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1869 for (const auto &timing : send_timings_) {
1870 timing_offsets.push_back(
1871 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1872 }
1873 send_timings_.clear();
1874 flatbuffers::Offset<
1875 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1876 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1877 timing::ReplayTiming::Builder timing_builder =
1878 builder.MakeBuilder<timing::ReplayTiming>();
1879 timing_builder.add_messages(timings_offset);
1880 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1881}
1882
Austin Schuh287d43d2020-12-04 20:19:33 -08001883bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1884 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001885 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001886 uint32_t remote_queue_index = 0xffffffff;
1887
Austin Schuh287d43d2020-12-04 20:19:33 -08001888 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001889 State *source_state =
1890 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001891 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001892 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001893 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001894
Austin Schuh9942bae2021-01-07 22:06:44 -08001895 struct SentTimestamp {
1896 monotonic_clock::time_point monotonic_event_time;
1897 uint32_t queue_index;
1898 } search;
1899
Austin Schuh58646e22021-08-23 23:51:46 -07001900 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1901 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001902 search.monotonic_event_time =
1903 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001904 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001905
1906 // Find the sent time if available.
1907 auto element = std::lower_bound(
1908 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001909 [](ContiguousSentTimestamp a, SentTimestamp b) {
1910 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001911 return true;
1912 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001913 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001914 return false;
1915 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001916
1917 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001918 return true;
1919 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001920 if (a.starting_queue_index >= b.queue_index) {
1921 return false;
1922 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001923
Austin Schuh9942bae2021-01-07 22:06:44 -08001924 // If it isn't clearly below or above, it is below. Since we return
1925 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001926 return false;
1927 });
1928
1929 // TODO(austin): Be a bit more principled here, but we will want to do that
1930 // after the logger rewrite. We hit this when one node finishes, but the
1931 // other node isn't done yet. So there is no send time, but there is a
1932 // receive time.
1933 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001934 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1935 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001936
1937 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001938 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001939 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001940 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001941 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001942 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001943 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001944 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001945
Austin Schuh58646e22021-08-23 23:51:46 -07001946 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001947 element->actual_queue_index -
1948 element->starting_queue_index;
1949 } else {
1950 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001951 }
Austin Schuh58646e22021-08-23 23:51:46 -07001952 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1953 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001954 }
1955
James Kuszmaul09632422022-05-25 15:56:19 -07001956 if (event_loop_factory_ != nullptr &&
1957 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1958 multinode_filters_ != nullptr) {
1959 // Sanity check that we are using consistent boot uuids.
1960 State *source_state =
1961 channel_source_state_[timestamped_message.channel_index];
1962 CHECK_EQ(multinode_filters_->boot_uuid(
1963 configuration::GetNodeIndex(event_loop_->configuration(),
1964 source_state->node()),
1965 timestamped_message.monotonic_remote_time.boot),
1966 CHECK_NOTNULL(
1967 CHECK_NOTNULL(
1968 channel_source_state_[timestamped_message.channel_index])
1969 ->event_loop_)
1970 ->boot_uuid());
1971 }
1972
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001973 // Send! Use the replayed queue index here instead of the logged queue index
1974 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001975 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001976 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001977 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001978 timestamped_message.realtime_remote_time, remote_queue_index,
1979 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001980 ? CHECK_NOTNULL(multinode_filters_)
1981 ->boot_uuid(configuration::GetNodeIndex(
1982 event_loop_->configuration(),
1983 channel_source_state_[timestamped_message
1984 .channel_index]
1985 ->node()),
1986 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001987 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001988 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001989 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1990 timestamped_message.monotonic_event_time.time) {
1991 // Only track errors for non-fetched messages.
1992 TrackMessageSendTiming(
1993 *sender,
1994 timestamped_message.monotonic_event_time.time + clock_offset());
1995 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001996
Austin Schuh287d43d2020-12-04 20:19:33 -08001997 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001998 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001999 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
2000 // Nothing here, start a range with 0 length.
2001 ContiguousSentTimestamp timestamp;
2002 timestamp.starting_monotonic_event_time =
2003 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002004 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002005 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002006 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002007 timestamp.actual_queue_index = sender->sent_queue_index();
2008 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2009 timestamp);
2010 } else {
2011 // We've got something. See if the next timestamp is still contiguous. If
2012 // so, grow it.
2013 ContiguousSentTimestamp *back =
2014 &queue_index_map_[timestamped_message.channel_index]->back();
2015 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002016 (timestamped_message.queue_index.index -
2017 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002018 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002019 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002020 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002021 } else {
2022 // Otherwise, make a new one.
2023 ContiguousSentTimestamp timestamp;
2024 timestamp.starting_monotonic_event_time =
2025 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002026 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002027 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002028 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002029 timestamp.actual_queue_index = sender->sent_queue_index();
2030 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2031 timestamp);
2032 }
2033 }
2034
2035 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2036 // queue index diverge a couple of elements, which would be a very small
2037 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002038 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2039 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002040 // TODO(james): Currently, If running replay against a single event loop,
2041 // remote timestamps will not get replayed because this code-path only
2042 // gets triggered on the event loop that receives the forwarded message
2043 // that the timestamps correspond to. This code, as written, also doesn't
2044 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002045 State *source_state =
2046 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2047
Austin Schuh969cd602021-01-03 00:09:45 -08002048 flatbuffers::FlatBufferBuilder fbb;
2049 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002050 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2051 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002052
Austin Schuh969cd602021-01-03 00:09:45 -08002053 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002054
2055 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002056 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002057
2058 // Swap the remote and sent metrics. They are from the sender's
2059 // perspective, not the receiver's perspective.
2060 message_header_builder.add_monotonic_sent_time(
2061 sender->monotonic_sent_time().time_since_epoch().count());
2062 message_header_builder.add_realtime_sent_time(
2063 sender->realtime_sent_time().time_since_epoch().count());
2064 message_header_builder.add_queue_index(sender->sent_queue_index());
2065
Austin Schuh58646e22021-08-23 23:51:46 -07002066 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2067 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002068 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002069 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2070 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002071 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002072 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002073
2074 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002075 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002076
Austin Schuh969cd602021-01-03 00:09:45 -08002077 fbb.Finish(message_header_builder.Finish());
2078
2079 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2080 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002081 timestamped_message.monotonic_timestamp_time,
2082 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002083 }
2084
2085 return true;
2086}
2087
Austin Schuh969cd602021-01-03 00:09:45 -08002088LogReader::RemoteMessageSender::RemoteMessageSender(
2089 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2090 : event_loop_(event_loop),
2091 sender_(std::move(sender)),
2092 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2093
2094void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2095 if (remote_timestamps_.empty()) {
2096 CHECK_NOTNULL(timer_);
2097 timer_->Disable();
2098 scheduled_time_ = monotonic_clock::min_time;
2099 return;
2100 }
2101
2102 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2103 CHECK_NOTNULL(timer_);
Philipp Schradera6712522023-07-05 20:25:11 -07002104 timer_->Schedule(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002105 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002106 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2107 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002108 }
2109}
2110
2111void LogReader::RemoteMessageSender::Send(
2112 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002113 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002114 // There are 2 variants of logs.
2115 // 1) Logs without monotonic_timestamp_time
2116 // 2) Logs with monotonic_timestamp_time
2117 //
2118 // As of Jan 2021, we shouldn't have any more logs without
2119 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2120 // the effort of saving.
2121 //
2122 // This gives us 3 cases, 2 of which are undistinguishable.
2123 // 1) Old log without monotonic_timestamp_time.
2124 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2125 // remotely so we actually have monotonic_timestamp_time.
2126 // 3) New log, but the timestamp was logged on the node receiving the message
2127 // so there is no monotonic_timestamp_time.
2128 //
2129 // Our goal when replaying is to accurately reproduce the state of the world
2130 // present when logging. If a timestamp wasn't sent back across the network,
2131 // we shouldn't replay one back across the network.
2132 //
2133 // Given that we don't really care about 1, we can use the presence of the
2134 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2135 // monotonic_timestamp_time, this means the message was logged locally and
2136 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002137 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002138 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002139 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002140
Austin Schuh58646e22021-08-23 23:51:46 -07002141 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2142
Austin Schuhc41d6a82021-07-16 14:49:23 -07002143 remote_timestamps_.emplace(
2144 std::upper_bound(
2145 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002146 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002147 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2148 const Timestamp &timestamp) {
2149 return monotonic_timestamp_time <
2150 timestamp.monotonic_timestamp_time;
2151 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002152 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002153 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002154}
2155
2156void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002157 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2158 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002159 CHECK(!remote_timestamps_.empty());
2160
2161 // Send out all timestamps at the currently scheduled time.
2162 while (remote_timestamps_.front().monotonic_timestamp_time ==
2163 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002164 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2165 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002166 remote_timestamps_.pop_front();
2167 if (remote_timestamps_.empty()) {
2168 break;
2169 }
2170 }
2171 scheduled_time_ = monotonic_clock::min_time;
2172
2173 ScheduleTimestamp();
2174}
2175
2176LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002177 const Channel *channel, const Connection *connection) {
2178 message_bridge::ChannelTimestampFinder finder(event_loop_);
2179 // Look at any pre-created channel/connection pairs.
2180 {
2181 auto it =
2182 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2183 if (it != channel_timestamp_loggers_.end()) {
2184 return it->second.get();
2185 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002186 }
2187
Austin Schuh61e973f2021-02-21 21:43:56 -08002188 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2189 // to.
2190 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2191
2192 {
2193 // See if that has been created before. If so, cache it in
2194 // channel_timestamp_loggers_ and return.
2195 auto it = timestamp_loggers_.find(timestamp_channel);
2196 if (it != timestamp_loggers_.end()) {
2197 CHECK(channel_timestamp_loggers_
2198 .try_emplace(std::make_pair(channel, connection), it->second)
2199 .second);
2200 return it->second.get();
2201 }
2202 }
2203
2204 // Otherwise, make a sender, save it, and cache it.
2205 auto result = channel_timestamp_loggers_.try_emplace(
2206 std::make_pair(channel, connection),
2207 std::make_shared<RemoteMessageSender>(
2208 event_loop()->MakeSender<RemoteMessage>(
2209 timestamp_channel->name()->string_view()),
2210 event_loop()));
2211
2212 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2213 .second);
2214 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002215}
2216
Austin Schuhdda74ec2021-01-03 19:30:37 -08002217TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002218 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002219 if (message_queuer_.has_value()) {
2220 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2221 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2222 message_queuer_->SetState(
2223 message.value().monotonic_event_time +
2224 std::chrono::duration_cast<std::chrono::nanoseconds>(
2225 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2226 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002227 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002228 CHECK(timestamp_mapper_ != nullptr);
2229 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2230 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002231
James Kuszmaula16a7912022-06-17 10:58:12 -07002232 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002233
James Kuszmaula16a7912022-06-17 10:58:12 -07002234 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2235 << result.monotonic_event_time;
2236 timestamp_mapper_->PopFront();
2237 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002238
James Kuszmaula16a7912022-06-17 10:58:12 -07002239 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002240
James Kuszmaula16a7912022-06-17 10:58:12 -07002241 VLOG(1) << "Popped " << result
2242 << configuration::CleanedChannelToString(
2243 event_loop_->configuration()->channels()->Get(
2244 factory_channel_index_[result.channel_index]));
2245 return result;
2246 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002247}
2248
James Kuszmaula16a7912022-06-17 10:58:12 -07002249BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2250 if (!message_queuer_.has_value()) {
2251 return SingleThreadedOldestMessageTime();
2252 }
2253 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2254 if (!message.has_value()) {
2255 return BootTimestamp::max_time();
2256 }
2257 if (message.value().monotonic_event_time.boot == boot_count()) {
2258 ObserveNextMessage(message.value().monotonic_event_time.time,
2259 message.value().realtime_event_time);
2260 }
2261 return message.value().monotonic_event_time;
2262}
2263
2264BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2265 CHECK(!message_queuer_.has_value())
2266 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2267 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002268 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002269 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002270 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002271 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2272 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002273 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002274 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002275 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002276 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002277 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2278 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2279 result_ptr->realtime_event_time);
2280 }
Austin Schuh58646e22021-08-23 23:51:46 -07002281 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002282}
2283
2284void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002285 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002286
Austin Schuhe639ea12021-01-25 13:00:22 -08002287 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2288 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002289}
2290
2291void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002292 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002293 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002294 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002295 for (size_t i = 0; i < channels_.size(); ++i) {
2296 channels_[i].reset();
2297 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002298 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002299 channel_timestamp_loggers_.clear();
2300 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002301 event_loop_unique_ptr_.reset();
2302 event_loop_ = nullptr;
2303 timer_handler_ = nullptr;
2304 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002305 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002306}
2307
Austin Schuhe33c08d2022-02-03 18:15:21 -08002308void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2309 if (start_time != realtime_clock::min_time) {
2310 start_event_notifier_ = std::make_unique<EventNotifier>(
2311 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2312 }
2313}
2314
2315void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2316 if (end_time != realtime_clock::max_time) {
2317 end_event_notifier_ = std::make_unique<EventNotifier>(
2318 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2319 }
2320}
2321
2322void LogReader::State::ObserveNextMessage(
2323 monotonic_clock::time_point monotonic_event,
2324 realtime_clock::time_point realtime_event) {
2325 if (start_event_notifier_) {
2326 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2327 }
2328 if (end_event_notifier_) {
2329 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2330 }
2331}
2332
2333void LogReader::State::ClearTimeFlags() {
2334 start_event_notifier_.reset();
2335 end_event_notifier_.reset();
2336}
2337
2338void LogReader::State::NotifyLogfileStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002339 // If the start_event_notifier_ is set, that means that a realtime start time
2340 // was set manually; when the override is set, we want to delay any startup
2341 // handlers that would've happened before requested start time until that
2342 // start time.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002343 if (start_event_notifier_) {
Philipp Schrader790cb542023-07-05 21:06:52 -07002344 // Only call OnStart() if the start time for this node
2345 // (realtime_start_time())
Austin Schuhe33c08d2022-02-03 18:15:21 -08002346 if (start_event_notifier_->realtime_event_time() >
2347 realtime_start_time(boot_count())) {
2348 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2349 << " > " << realtime_start_time(boot_count());
2350 return;
2351 }
2352 }
2353 if (found_last_message_) {
2354 VLOG(1) << "Last message already found, bailing";
2355 return;
2356 }
2357 RunOnStart();
2358}
2359
2360void LogReader::State::NotifyFlagStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002361 // Should only be called if start_event_notifier_ has been set (which happens
2362 // as part of setting an explicit start time); only call the startup functions
2363 // that occurred *before* the start flag value.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002364 if (start_event_notifier_->realtime_event_time() >=
2365 realtime_start_time(boot_count())) {
2366 RunOnStart();
2367 }
2368}
2369
2370void LogReader::State::NotifyLogfileEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002371 // Don't execute the OnEnd handlers if the logfile was ended artifically
2372 // early.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002373 if (found_last_message_) {
2374 return;
2375 }
2376
James Kuszmaul82c3b512023-07-08 20:25:41 -07002377 // Ensure that we only call OnEnd() if OnStart() was already called for this
2378 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002379 if (!stopped_ && started_) {
2380 RunOnEnd();
2381 }
2382}
2383
2384void LogReader::State::NotifyFlagEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002385 // Ensure that we only call OnEnd() if OnStart() was already called for this
2386 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002387 if (!stopped_ && started_) {
2388 RunOnEnd();
2389 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002390 CHECK(notice_realtime_end_);
2391 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002392 }
2393}
2394
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002395void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002396 if (node_event_loop_factory_ == nullptr) {
2397 // If not running with simulated event loop, set the monotonic clock
2398 // offset.
2399 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2400
2401 if (start_event_notifier_) {
2402 start_event_notifier_->SetClockOffset(clock_offset_);
2403 }
2404 if (end_event_notifier_) {
2405 end_event_notifier_->SetClockOffset(clock_offset_);
2406 }
2407 }
2408}
2409
James Kuszmaulb67409b2022-06-20 16:25:03 -07002410void LogReader::SetRealtimeReplayRate(double replay_rate) {
2411 CHECK(event_loop_factory_ != nullptr)
2412 << ": Can't set replay rate without an event loop factory (have you "
2413 "called Register()?).";
2414 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2415}
2416
James Kuszmaulb11a1502022-07-01 16:02:25 -07002417void LogReader::NoticeRealtimeEnd() {
2418 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2419 --live_nodes_with_realtime_time_end_;
2420 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2421 event_loop_factory_ != nullptr) {
2422 event_loop_factory_->Exit();
2423 }
2424}
2425
Austin Schuhe309d2a2019-11-29 13:25:21 -08002426} // namespace logger
2427} // namespace aos