blob: be49393d391f2c9b31f9a1a63241d79f1a82e642 [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
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08007
Tyler Chatowbf0609c2021-07-31 16:13:27 -07008#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -08009#include <vector>
10
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070014#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070015#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080016#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070018#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080019#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080020#include "aos/network/remote_message_generated.h"
21#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080022#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080023#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070025#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070026#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080028#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080029
Austin Schuh15649d62019-12-28 16:36:38 -080030DEFINE_bool(skip_missing_forwarding_entries, false,
31 "If true, drop any forwarding entries with missing data. If "
32 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080033
Austin Schuh0ca1fd32020-12-18 22:53:05 -080034DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080035
Austin Schuh2f8fd752020-09-01 22:38:28 -070036DEFINE_bool(skip_order_validation, false,
37 "If true, ignore any out of orderness in replay");
38
Austin Schuhf0688662020-12-19 15:37:45 -080039DEFINE_double(
40 time_estimation_buffer_seconds, 2.0,
41 "The time to buffer ahead in the log file to accurately reconstruct time.");
42
Austin Schuhe33c08d2022-02-03 18:15:21 -080043DEFINE_string(
44 start_time, "",
45 "If set, start at this point in time in the log on the realtime clock.");
46DEFINE_string(
47 end_time, "",
48 "If set, end at this point in time in the log on the realtime clock.");
49
James Kuszmaul09632422022-05-25 15:56:19 -070050DEFINE_bool(drop_realtime_messages_before_start, false,
51 "If set, will drop any messages sent before the start of the "
52 "logfile in realtime replay. Setting this guarantees consistency "
53 "in timing with the original logfile, but means that you lose "
54 "access to fetched low-frequency messages.");
55
James Kuszmaula16a7912022-06-17 10:58:12 -070056DEFINE_double(
57 threaded_look_ahead_seconds, 2.0,
58 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
59 "Can validly be zero, but higher values are encouraged for realtime replay "
60 "in order to prevent the replay from ever having to block on waiting for "
61 "the reader to find the next message.");
62
Austin Schuhe309d2a2019-11-29 13:25:21 -080063namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070064namespace configuration {
65// We don't really want to expose this publicly, but log reader doesn't really
66// want to re-implement it.
67void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
68 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070069} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080070namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070071namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080072
Austin Schuh1c227352021-09-17 12:53:54 -070073bool CompareChannels(const Channel *c,
74 ::std::pair<std::string_view, std::string_view> p) {
75 int name_compare = c->name()->string_view().compare(p.first);
76 if (name_compare == 0) {
77 return c->type()->string_view() < p.second;
78 } else if (name_compare < 0) {
79 return true;
80 } else {
81 return false;
82 }
83}
84
85bool EqualsChannels(const Channel *c,
86 ::std::pair<std::string_view, std::string_view> p) {
87 return c->name()->string_view() == p.first &&
88 c->type()->string_view() == p.second;
89}
90
Austin Schuh0de30f32020-12-06 12:44:28 -080091// Copies the channel, removing the schema as we go. If new_name is provided,
92// it is used instead of the name inside the channel. If new_type is provided,
93// it is used instead of the type in the channel.
94flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
95 std::string_view new_name,
96 std::string_view new_type,
97 flatbuffers::FlatBufferBuilder *fbb) {
98 flatbuffers::Offset<flatbuffers::String> name_offset =
99 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
100 : new_name);
101 flatbuffers::Offset<flatbuffers::String> type_offset =
102 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
103 flatbuffers::Offset<flatbuffers::String> source_node_offset =
104 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
105 : 0;
106
107 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
108 destination_nodes_offset =
109 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
110
111 flatbuffers::Offset<
112 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
113 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
114
115 Channel::Builder channel_builder(*fbb);
116 channel_builder.add_name(name_offset);
117 channel_builder.add_type(type_offset);
118 if (c->has_frequency()) {
119 channel_builder.add_frequency(c->frequency());
120 }
121 if (c->has_max_size()) {
122 channel_builder.add_max_size(c->max_size());
123 }
124 if (c->has_num_senders()) {
125 channel_builder.add_num_senders(c->num_senders());
126 }
127 if (c->has_num_watchers()) {
128 channel_builder.add_num_watchers(c->num_watchers());
129 }
130 if (!source_node_offset.IsNull()) {
131 channel_builder.add_source_node(source_node_offset);
132 }
133 if (!destination_nodes_offset.IsNull()) {
134 channel_builder.add_destination_nodes(destination_nodes_offset);
135 }
136 if (c->has_logger()) {
137 channel_builder.add_logger(c->logger());
138 }
139 if (!logger_nodes_offset.IsNull()) {
140 channel_builder.add_logger_nodes(logger_nodes_offset);
141 }
142 if (c->has_read_method()) {
143 channel_builder.add_read_method(c->read_method());
144 }
145 if (c->has_num_readers()) {
146 channel_builder.add_num_readers(c->num_readers());
147 }
148 return channel_builder.Finish();
149}
150
Austin Schuhe309d2a2019-11-29 13:25:21 -0800151namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800152using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700153} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800154
Austin Schuhe33c08d2022-02-03 18:15:21 -0800155// Class to manage triggering events on the RT clock while replaying logs. Since
156// the RT clock can only change when we get a message, we only need to update
157// our timers when new messages are read.
158class EventNotifier {
159 public:
160 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
161 std::string_view name,
162 realtime_clock::time_point realtime_event_time)
163 : event_loop_(event_loop),
164 fn_(std::move(fn)),
165 realtime_event_time_(realtime_event_time) {
166 CHECK(event_loop_);
167 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
168
169 if (event_loop_->node() != nullptr) {
170 event_timer_->set_name(
171 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
172 } else {
173 event_timer_->set_name(name);
174 }
175 }
176
177 ~EventNotifier() { event_timer_->Disable(); }
178
James Kuszmaul09632422022-05-25 15:56:19 -0700179 // Sets the clock offset for realtime playback.
180 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
181 clock_offset_ = clock_offset;
182 }
183
Austin Schuhe33c08d2022-02-03 18:15:21 -0800184 // Returns the event trigger time.
185 realtime_clock::time_point realtime_event_time() const {
186 return realtime_event_time_;
187 }
188
189 // Observes the next message and potentially calls the callback or updates the
190 // timer.
191 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
192 realtime_clock::time_point realtime_message_time) {
193 if (realtime_message_time < realtime_event_time_) {
194 return;
195 }
196 if (called_) {
197 return;
198 }
199
200 // Move the callback wakeup time to the correct time (or make it now if
201 // there's a gap in time) now that we know it is before the next
202 // message.
203 const monotonic_clock::time_point candidate_monotonic =
204 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
205 const monotonic_clock::time_point monotonic_now =
206 event_loop_->monotonic_now();
207 if (candidate_monotonic < monotonic_now) {
208 // Whops, time went backwards. Just do it now.
209 HandleTime();
210 } else {
James Kuszmaul09632422022-05-25 15:56:19 -0700211 event_timer_->Setup(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800212 }
213 }
214
215 private:
216 void HandleTime() {
217 if (!called_) {
218 called_ = true;
219 fn_();
220 }
221 }
222
223 EventLoop *event_loop_ = nullptr;
224 TimerHandler *event_timer_ = nullptr;
225 std::function<void()> fn_;
226
227 const realtime_clock::time_point realtime_event_time_ =
228 realtime_clock::min_time;
229
James Kuszmaul09632422022-05-25 15:56:19 -0700230 std::chrono::nanoseconds clock_offset_{0};
231
Austin Schuhe33c08d2022-02-03 18:15:21 -0800232 bool called_ = false;
233};
234
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800235LogReader::LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700236 const Configuration *replay_configuration,
237 const ReplayChannels *replay_channels)
238 : LogReader(SortParts({std::string(filename)}), replay_configuration,
239 replay_channels) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800240
Austin Schuh287d43d2020-12-04 20:19:33 -0800241LogReader::LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700242 const Configuration *replay_configuration,
243 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800244 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700245 replay_configuration_(replay_configuration),
246 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800247 SetStartTime(FLAGS_start_time);
248 SetEndTime(FLAGS_end_time);
249
Austin Schuh0ca51f32020-12-25 21:51:45 -0800250 CHECK_GT(log_files_.size(), 0u);
251 {
252 // Validate that we have the same config everwhere. This will be true if
253 // all the parts were sorted together and the configs match.
254 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800255 for (const LogFile &log_file : log_files_) {
256 if (log_file.config.get() == nullptr) {
257 LOG(FATAL) << "Couldn't find a config in " << log_file;
258 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800259 if (config == nullptr) {
260 config = log_file.config.get();
261 } else {
262 CHECK_EQ(config, log_file.config.get());
263 }
264 }
265 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800266
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700267 if (replay_channels_ != nullptr) {
268 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
269 "no messages will get replayed.";
270 }
271
Austin Schuh6331ef92020-01-07 18:28:09 -0800272 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800273
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700274 // Remap all existing remote timestamp channels. They will be recreated, and
275 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700276 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800277 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
278 "log_reader", node);
279
280 absl::btree_set<std::string_view> remote_nodes;
281
282 for (const Channel *channel : *logged_configuration()->channels()) {
283 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
284 continue;
285 }
286 if (!channel->has_destination_nodes()) {
287 continue;
288 }
289 for (const Connection *connection : *channel->destination_nodes()) {
290 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
291 node)) {
292 // Start by seeing if the split timestamp channels are being used for
293 // this message. If so, remap them.
294 const Channel *timestamp_channel = configuration::GetChannel(
295 logged_configuration(),
296 finder.SplitChannelName(channel, connection),
297 RemoteMessage::GetFullyQualifiedName(), "", node, true);
298
299 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700300 // If for some reason a timestamp channel is not NOT_LOGGED (which
301 // is unusual), then remap the channel so that the replayed channel
302 // doesn't overlap with the special separate replay we do for
303 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800304 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
305 RemapLoggedChannel<RemoteMessage>(
306 timestamp_channel->name()->string_view(), node);
307 }
308 continue;
309 }
310
311 // Otherwise collect this one up as a node to look for a combined
312 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700313 LOG(WARNING) << "Failed to find channel "
314 << finder.SplitChannelName(channel, connection)
315 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800316 remote_nodes.insert(connection->name()->string_view());
317 }
318 }
319 }
320
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700321 std::vector<const Node *> timestamp_logger_nodes =
322 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800323 for (const std::string_view remote_node : remote_nodes) {
324 const std::string channel = finder.CombinedChannelName(remote_node);
325
Austin Schuh0de30f32020-12-06 12:44:28 -0800326 // See if the log file is an old log with MessageHeader channels in it, or
327 // a newer log with RemoteMessage. If we find an older log, rename the
328 // type too along with the name.
329 if (HasChannel<MessageHeader>(channel, node)) {
330 CHECK(!HasChannel<RemoteMessage>(channel, node))
331 << ": Can't have both a MessageHeader and RemoteMessage remote "
332 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800333 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
334 // careful about updating the config, but there are fewer and fewer logs
335 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800336 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
337 "aos.message_bridge.RemoteMessage");
338 } else {
339 CHECK(HasChannel<RemoteMessage>(channel, node))
340 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
341 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
342 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800343 // Only bother to remap if there's something on the channel. We can
344 // tell if the channel was marked NOT_LOGGED or not. This makes the
345 // config not change un-necesarily when we replay a log with NOT_LOGGED
346 // messages.
347 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
348 RemapLoggedChannel<RemoteMessage>(channel, node);
349 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800350 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700351 }
352 }
353
Austin Schuh6aa77be2020-02-22 21:06:40 -0800354 if (replay_configuration) {
355 CHECK_EQ(configuration::MultiNode(configuration()),
356 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700357 << ": Log file and replay config need to both be multi or single "
358 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800359 }
360
Austin Schuh6f3babe2020-01-26 20:34:50 -0800361 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700362 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800363 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800364 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700365 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800366 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700367 << ": Log file and replay config need to have matching nodes "
368 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700369 for (const Node *node : *logged_configuration()->nodes()) {
370 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700371 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
372 << " in logged config that is not present in the replay "
373 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700374 }
375 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800376 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800377 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800378 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800379}
380
Austin Schuh6aa77be2020-02-22 21:06:40 -0800381LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700382 if (event_loop_factory_unique_ptr_) {
383 Deregister();
384 } else if (event_loop_factory_ != nullptr) {
385 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
386 "is destroyed";
387 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700388 // Zero out some buffers. It's easy to do use-after-frees on these, so make
389 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700390 if (remapped_configuration_buffer_) {
391 remapped_configuration_buffer_->Wipe();
392 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800393}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800394
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800395const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800396 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800397}
398
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800399const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800400 return remapped_configuration_;
401}
402
Austin Schuh07676622021-01-21 18:59:17 -0800403std::vector<const Node *> LogReader::LoggedNodes() const {
404 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800405}
Austin Schuh15649d62019-12-28 16:36:38 -0800406
Austin Schuh11d43732020-09-21 17:28:30 -0700407monotonic_clock::time_point LogReader::monotonic_start_time(
408 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800409 State *state =
410 states_[configuration::GetNodeIndex(configuration(), node)].get();
411 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
412
Austin Schuhf665eb42022-02-03 18:26:25 -0800413 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800414}
415
Austin Schuh11d43732020-09-21 17:28:30 -0700416realtime_clock::time_point LogReader::realtime_start_time(
417 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800418 State *state =
419 states_[configuration::GetNodeIndex(configuration(), node)].get();
420 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
421
Austin Schuhf665eb42022-02-03 18:26:25 -0800422 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800423}
424
Austin Schuh58646e22021-08-23 23:51:46 -0700425void LogReader::OnStart(std::function<void()> fn) {
426 CHECK(!configuration::MultiNode(configuration()));
427 OnStart(nullptr, std::move(fn));
428}
429
430void LogReader::OnStart(const Node *node, std::function<void()> fn) {
431 const int node_index = configuration::GetNodeIndex(configuration(), node);
432 CHECK_GE(node_index, 0);
433 CHECK_LT(node_index, static_cast<int>(states_.size()));
434 State *state = states_[node_index].get();
435 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
436
437 state->OnStart(std::move(fn));
438}
439
James Kuszmaula16a7912022-06-17 10:58:12 -0700440void LogReader::State::QueueThreadUntil(BootTimestamp time) {
441 if (threading_ == ThreadedBuffering::kYes) {
442 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
443 message_queuer_.emplace(
444 [this](const BootTimestamp queue_until) {
445 // This will be called whenever anything prompts us for any state
446 // change; there may be wakeups that result in us not having any new
447 // data to push (even if we aren't done), in which case we will return
448 // nullopt but not done().
449 if (last_queued_message_.has_value() &&
450 queue_until < last_queued_message_) {
451 return util::ThreadedQueue<TimestampedMessage,
452 BootTimestamp>::PushResult{
453 std::nullopt, false,
454 last_queued_message_ == BootTimestamp::max_time()};
455 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700456
James Kuszmaula16a7912022-06-17 10:58:12 -0700457 TimestampedMessage *message = timestamp_mapper_->Front();
458 // Upon reaching the end of the log, exit.
459 if (message == nullptr) {
460 last_queued_message_ = BootTimestamp::max_time();
461 return util::ThreadedQueue<TimestampedMessage,
462 BootTimestamp>::PushResult{std::nullopt,
463 false, true};
464 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700465
James Kuszmaula16a7912022-06-17 10:58:12 -0700466 last_queued_message_ = message->monotonic_event_time;
467 const util::ThreadedQueue<TimestampedMessage,
468 BootTimestamp>::PushResult result{
469 *message, queue_until >= last_queued_message_, false};
470 timestamp_mapper_->PopFront();
471 SeedSortedMessages();
472 return result;
473 },
474 time);
475 // Spin until the first few seconds of messages are queued up so that we
476 // don't end up with delays/inconsistent timing during the first few seconds
477 // of replay.
478 message_queuer_->WaitForNoMoreWork();
479 }
480}
481
Austin Schuh58646e22021-08-23 23:51:46 -0700482void LogReader::State::OnStart(std::function<void()> fn) {
483 on_starts_.emplace_back(std::move(fn));
484}
485
486void LogReader::State::RunOnStart() {
487 SetRealtimeOffset(monotonic_start_time(boot_count()),
488 realtime_start_time(boot_count()));
489
490 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
491 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800492 auto fn = [this]() {
493 for (size_t i = 0; i < on_starts_.size(); ++i) {
494 on_starts_[i]();
495 }
496 };
497 if (event_loop_factory_) {
498 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
499 } else {
500 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700501 }
502 stopped_ = false;
503 started_ = true;
504}
505
506void LogReader::OnEnd(std::function<void()> fn) {
507 CHECK(!configuration::MultiNode(configuration()));
508 OnEnd(nullptr, std::move(fn));
509}
510
511void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
512 const int node_index = configuration::GetNodeIndex(configuration(), node);
513 CHECK_GE(node_index, 0);
514 CHECK_LT(node_index, static_cast<int>(states_.size()));
515 State *state = states_[node_index].get();
516 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
517
518 state->OnEnd(std::move(fn));
519}
520
521void LogReader::State::OnEnd(std::function<void()> fn) {
522 on_ends_.emplace_back(std::move(fn));
523}
524
525void LogReader::State::RunOnEnd() {
526 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
527 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800528 auto fn = [this]() {
529 for (size_t i = 0; i < on_ends_.size(); ++i) {
530 on_ends_[i]();
531 }
532 };
533 if (event_loop_factory_) {
534 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
535 } else {
536 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700537 }
538
539 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800540 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700541 if (message_queuer_.has_value()) {
542 message_queuer_->StopPushing();
543 }
Austin Schuh58646e22021-08-23 23:51:46 -0700544}
545
James Kuszmaul94ca5132022-07-19 09:11:08 -0700546std::vector<
547 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
548LogReader::State::NonExclusiveChannels() {
549 CHECK_NOTNULL(node_event_loop_factory_);
550 const aos::Configuration *config = node_event_loop_factory_->configuration();
551 std::vector<
552 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
553 result{// Timing reports can be sent by logged and replayed applications.
554 {aos::configuration::GetChannel(config, "/aos",
555 "aos.timing.Report", "", node_),
556 NodeEventLoopFactory::ExclusiveSenders::kNo},
557 // AOS_LOG may be used in the log and in replay.
558 {aos::configuration::GetChannel(
559 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
560 NodeEventLoopFactory::ExclusiveSenders::kNo}};
561 for (const Node *const node : configuration::GetNodes(config)) {
562 if (node == nullptr) {
563 break;
564 }
565 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
566 config,
567 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700568 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700569 // The old-style remote timestamp channel can be populated from any
570 // channel, simulated or replayed.
571 if (old_timestamp_channel != nullptr) {
572 result.push_back(std::make_pair(
573 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
574 }
575 }
576 // Remove any channels that weren't found due to not existing in the
577 // config.
578 for (size_t ii = 0; ii < result.size();) {
579 if (result[ii].first == nullptr) {
580 result.erase(result.begin() + ii);
581 } else {
582 ++ii;
583 }
584 }
585 return result;
586}
587
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800588void LogReader::Register() {
589 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800590 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800591 Register(event_loop_factory_unique_ptr_.get());
592}
593
Austin Schuh58646e22021-08-23 23:51:46 -0700594void LogReader::RegisterWithoutStarting(
595 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800596 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700597 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800598 filters_ =
599 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800600 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700601 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800602 chrono::duration_cast<chrono::nanoseconds>(
603 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800604
Austin Schuhe639ea12021-01-25 13:00:22 -0800605 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700606 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800607 const size_t node_index =
608 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800609 std::vector<LogParts> filtered_parts = FilterPartsForNode(
610 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800611
James Kuszmaula16a7912022-06-17 10:58:12 -0700612 // We don't run with threading on the buffering for simulated event loops
613 // because we haven't attempted to validate how the interactions beteen the
614 // buffering and the timestamp mapper works when running multiple nodes
615 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800616 states_[node_index] = std::make_unique<State>(
617 filtered_parts.size() == 0u
618 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700619 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700620 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800621 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node));
Austin Schuh8bd96322020-02-13 21:18:22 -0800622 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700623 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800624 event_loop_factory_->GetNodeEventLoopFactory(node),
625 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700626
627 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800628 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800629 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800630 filters_->SetTimestampMappers(std::move(timestamp_mappers));
631
632 // Note: this needs to be set before any times are pulled, or we won't observe
633 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800634 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700635
Austin Schuh287d43d2020-12-04 20:19:33 -0800636 for (const Node *node : configuration::GetNodes(configuration())) {
637 const size_t node_index =
638 configuration::GetNodeIndex(configuration(), node);
639 State *state = states_[node_index].get();
640 for (const Node *other_node : configuration::GetNodes(configuration())) {
641 const size_t other_node_index =
642 configuration::GetNodeIndex(configuration(), other_node);
643 State *other_state = states_[other_node_index].get();
644 if (other_state != state) {
645 state->AddPeer(other_state);
646 }
647 }
648 }
649
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700650 // Register after making all the State objects so we can build references
651 // between them.
652 for (const Node *node : configuration::GetNodes(configuration())) {
653 const size_t node_index =
654 configuration::GetNodeIndex(configuration(), node);
655 State *state = states_[node_index].get();
656
Austin Schuh58646e22021-08-23 23:51:46 -0700657 // If we didn't find any log files with data in them, we won't ever get a
658 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700659 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700660 continue;
661 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700662
Austin Schuh58646e22021-08-23 23:51:46 -0700663 ++live_nodes_;
664
665 NodeEventLoopFactory *node_factory =
666 event_loop_factory_->GetNodeEventLoopFactory(node);
667 node_factory->OnStartup([this, state, node]() {
668 RegisterDuringStartup(state->MakeEventLoop(), node);
669 });
670 node_factory->OnShutdown([this, state, node]() {
671 RegisterDuringStartup(nullptr, node);
672 state->DestroyEventLoop();
673 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700674 }
675
James Kuszmaul46d82582020-05-09 19:50:09 -0700676 if (live_nodes_ == 0) {
677 LOG(FATAL)
678 << "Don't have logs from any of the nodes in the replay config--are "
679 "you sure that the replay config matches the original config?";
680 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800681
Austin Schuh87dd3832021-01-01 23:07:31 -0800682 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800683
Austin Schuh858c9f32020-08-31 16:56:12 -0700684 for (std::unique_ptr<State> &state : states_) {
685 state->SeedSortedMessages();
686 }
687
Austin Schuh6f3babe2020-01-26 20:34:50 -0800688 // Forwarding is tracked per channel. If it is enabled, we want to turn it
689 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700690 // nodes, and also replayed on the other nodes. This may not satisfy all
691 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800692 if (configuration::MultiNode(event_loop_factory_->configuration())) {
693 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
694 const Channel *channel = logged_configuration()->channels()->Get(i);
695 const Node *node = configuration::GetNode(
696 configuration(), channel->source_node()->string_view());
697
Austin Schuh8bd96322020-02-13 21:18:22 -0800698 State *state =
699 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800700
701 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700702 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800703
704 event_loop_factory_->DisableForwarding(remapped_channel);
705 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700706
707 // If we are replaying a log, we don't want a bunch of redundant messages
708 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700709 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800710 }
Austin Schuh891214d2021-11-11 20:35:02 -0800711
712 // Write pseudo start times out to file now that we are all setup.
713 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700714}
715
716void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
717 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800718 StartAfterRegister(event_loop_factory);
719}
720
721void LogReader::StartAfterRegister(
722 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700723 // We want to start the log file at the last start time of the log files
724 // from all the nodes. Compute how long each node's simulation needs to run
725 // to move time to this point.
726 distributed_clock::time_point start_time = distributed_clock::min_time;
727
728 // TODO(austin): We want an "OnStart" callback for each node rather than
729 // running until the last node.
730
731 for (std::unique_ptr<State> &state : states_) {
732 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
733 << " for node " << MaybeNodeName(state->node()) << "now "
734 << state->monotonic_now();
735 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
736 continue;
737 }
738 // And start computing the start time on the distributed clock now that
739 // that works.
740 start_time = std::max(
741 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
742 }
743
744 // TODO(austin): If a node doesn't have a start time, we might not queue
745 // enough. If this happens, we'll explode with a frozen error eventually.
746
747 CHECK_GE(start_time, distributed_clock::epoch())
748 << ": Hmm, we have a node starting before the start of time. Offset "
749 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800750
Austin Schuhcde938c2020-02-02 17:30:07 -0800751 // While we are starting the system up, we might be relying on matching data
752 // to timestamps on log files where the timestamp log file starts before the
753 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800754 {
755 const bool prior_ignore_missing_data = ignore_missing_data_;
756 ignore_missing_data_ = true;
757 VLOG(1) << "Running until " << start_time << " in Register";
758 event_loop_factory_->RunFor(start_time.time_since_epoch());
759 VLOG(1) << "At start time";
760 // Now that we are running for real, missing data means that the log file is
761 // corrupted or went wrong.
762 ignore_missing_data_ = prior_ignore_missing_data;
763 }
Austin Schuh92547522019-12-28 14:33:43 -0800764
Austin Schuh8bd96322020-02-13 21:18:22 -0800765 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700766 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700767 if (state->realtime_start_time(0) != realtime_clock::min_time) {
768 state->SetRealtimeOffset(state->monotonic_start_time(0),
769 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700770 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700771 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
772 << " for node " << MaybeNodeName(state->event_loop()->node())
773 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700774 }
775
776 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800777 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800778 }
779}
780
Austin Schuh2f8fd752020-09-01 22:38:28 -0700781message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800782 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800783 if (filters_) {
784 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800785 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800786 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800787}
788
James Kuszmaul09632422022-05-25 15:56:19 -0700789// TODO(jkuszmaul): Make in-line modifications to
790// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
791// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800792void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700793 filters_ =
794 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
795 event_loop->configuration(), logged_configuration(),
796 log_files_[0].boots, FLAGS_skip_order_validation,
797 chrono::duration_cast<chrono::nanoseconds>(
798 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
799
800 std::vector<TimestampMapper *> timestamp_mappers;
801 for (const Node *node : configuration::GetNodes(configuration())) {
802 const size_t node_index =
803 configuration::GetNodeIndex(configuration(), node);
804 std::vector<LogParts> filtered_parts = FilterPartsForNode(
805 log_files_, node != nullptr ? node->name()->string_view() : "");
806
807 states_[node_index] = std::make_unique<State>(
808 filtered_parts.size() == 0u
809 ? nullptr
810 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700811 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800812 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node));
James Kuszmaul09632422022-05-25 15:56:19 -0700813 State *state = states_[node_index].get();
814
815 state->SetChannelCount(logged_configuration()->channels()->size());
816 timestamp_mappers.emplace_back(state->timestamp_mapper());
817 }
818
819 filters_->SetTimestampMappers(std::move(timestamp_mappers));
820
821 for (const Node *node : configuration::GetNodes(configuration())) {
822 const size_t node_index =
823 configuration::GetNodeIndex(configuration(), node);
824 State *state = states_[node_index].get();
825 for (const Node *other_node : configuration::GetNodes(configuration())) {
826 const size_t other_node_index =
827 configuration::GetNodeIndex(configuration(), other_node);
828 State *other_state = states_[other_node_index].get();
829 if (other_state != state) {
830 state->AddPeer(other_state);
831 }
832 }
833 }
834 for (const Node *node : configuration::GetNodes(configuration())) {
835 if (node == nullptr || node->name()->string_view() ==
836 event_loop->node()->name()->string_view()) {
837 Register(event_loop, event_loop->node());
838 } else {
839 Register(nullptr, node);
840 }
841 }
Austin Schuh58646e22021-08-23 23:51:46 -0700842}
843
844void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800845 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700846 states_[configuration::GetNodeIndex(configuration(), node)].get();
847
848 // If we didn't find any log files with data in them, we won't ever get a
849 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700850 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700851 return;
852 }
James Kuszmaul09632422022-05-25 15:56:19 -0700853
854 if (event_loop != nullptr) {
855 ++live_nodes_;
856 }
Austin Schuh58646e22021-08-23 23:51:46 -0700857
858 if (event_loop_factory_ != nullptr) {
859 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
860 [this, event_loop, node]() {
861 RegisterDuringStartup(event_loop, node);
862 });
863 } else {
864 RegisterDuringStartup(event_loop, node);
865 }
866}
867
868void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700869 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700870 CHECK(event_loop->configuration() == configuration());
871 }
872
873 State *state =
874 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800875
James Kuszmaul09632422022-05-25 15:56:19 -0700876 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800877 state->ClearTimeFlags();
878 }
879
Austin Schuh858c9f32020-08-31 16:56:12 -0700880 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800881
Tyler Chatow67ddb032020-01-12 14:30:04 -0800882 // We don't run timing reports when trying to print out logged data, because
883 // otherwise we would end up printing out the timing reports themselves...
884 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700885 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700886 event_loop->SkipTimingReport();
887 event_loop->SkipAosLog();
888 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800889
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700890 for (size_t logged_channel_index = 0;
891 logged_channel_index < logged_configuration()->channels()->size();
892 ++logged_channel_index) {
893 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700894 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700895 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800896
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700897 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700898 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700899
900 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700901
Austin Schuh58646e22021-08-23 23:51:46 -0700902 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
903 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700904 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700905 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800906
Austin Schuh58646e22021-08-23 23:51:46 -0700907 // We've got a message which is being forwarded to this node.
908 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700909
910 source_state =
911 states_[configuration::GetNodeIndex(configuration(), source_node)]
912 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800913 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700914
Austin Schuh58646e22021-08-23 23:51:46 -0700915 // We are the source, and it is forwarded.
916 const bool is_forwarded =
917 configuration::ChannelIsSendableOnNode(channel, node) &&
918 configuration::ConnectionCount(channel);
919
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700920 state->SetChannel(
921 logged_channel_index,
922 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700923 event_loop && logged &&
924 configuration::ChannelIsReadableOnNode(channel, node)
925 ? event_loop->MakeRawSender(channel)
926 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700927 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700928
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700929 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700930 const Node *source_node = configuration::GetNode(
931 configuration(), channel->source_node()->string_view());
932
933 for (const Connection *connection : *channel->destination_nodes()) {
934 const bool delivery_time_is_logged =
935 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
936 source_node);
937
938 if (delivery_time_is_logged) {
939 State *destination_state =
940 states_[configuration::GetNodeIndex(
941 configuration(), connection->name()->string_view())]
942 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700943 if (destination_state) {
944 destination_state->SetRemoteTimestampSender(
945 logged_channel_index,
946 event_loop ? state->RemoteTimestampSender(channel, connection)
947 : nullptr);
948 }
Austin Schuh58646e22021-08-23 23:51:46 -0700949 }
950 }
951 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800952 }
953
Austin Schuh58646e22021-08-23 23:51:46 -0700954 if (!event_loop) {
955 state->ClearRemoteTimestampSenders();
956 state->set_timer_handler(nullptr);
957 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800958 return;
959 }
960
Austin Schuh858c9f32020-08-31 16:56:12 -0700961 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700962 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800963 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700964 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700965 if (exit_on_finish_ && live_nodes_ == 0 &&
966 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700967 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800968 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800969 return;
970 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700971
Austin Schuhdda74ec2021-01-03 19:30:37 -0800972 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700973
974 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
975 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800976
Austin Schuhe309d2a2019-11-29 13:25:21 -0800977 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700978 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700979 if (event_loop_factory_ != nullptr) {
980 // Only enforce exact timing in simulation.
981 if (!FLAGS_skip_order_validation) {
982 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
983 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
984 << monotonic_now << " trying to send "
985 << timestamped_message.monotonic_event_time << " failure "
986 << state->DebugString();
987 } else if (BootTimestamp{.boot = state->boot_count(),
988 .time = monotonic_now} !=
989 timestamped_message.monotonic_event_time) {
990 LOG(WARNING) << "Check failed: monotonic_now == "
991 "timestamped_message.monotonic_event_time) ("
992 << monotonic_now << " vs. "
993 << timestamped_message.monotonic_event_time
994 << "): " << FlatbufferToJson(state->event_loop()->node())
995 << " Now " << monotonic_now << " trying to send "
996 << timestamped_message.monotonic_event_time << " failure "
997 << state->DebugString();
998 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700999 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001000
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001001 if (timestamped_message.monotonic_event_time.time >
1002 state->monotonic_start_time(
1003 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -07001004 event_loop_factory_ != nullptr ||
1005 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001006 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001007 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001008 BootTimestamp::min_time() &&
1009 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001010 // Confirm that the message was sent on the sending node before the
1011 // destination node (this node). As a proxy, do this by making sure
1012 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001013 //
1014 // TODO(austin): <= means that the cause message (which we know) could
1015 // happen after the effect even though we know they are at the same
1016 // time. I doubt anyone will notice for a bit, but we should really
1017 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001018 BootTimestamp monotonic_remote_now =
1019 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001020 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001021 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001022 monotonic_remote_now.boot)
1023 << state->event_loop()->node()->name()->string_view() << " to "
1024 << state->remote_node(timestamped_message.channel_index)
1025 ->name()
1026 ->string_view()
1027 << " while trying to send a message on "
1028 << configuration::CleanedChannelToString(
1029 logged_configuration()->channels()->Get(
1030 timestamped_message.channel_index))
1031 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001032 CHECK_LE(timestamped_message.monotonic_remote_time,
1033 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001034 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001035 << state->remote_node(timestamped_message.channel_index)
1036 ->name()
1037 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001038 << " while trying to send a message on "
1039 << configuration::CleanedChannelToString(
1040 logged_configuration()->channels()->Get(
1041 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001042 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001043 } else if (monotonic_remote_now.boot !=
1044 timestamped_message.monotonic_remote_time.boot) {
1045 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1046 << " vs "
1047 << timestamped_message.monotonic_remote_time.boot;
1048 } else if (timestamped_message.monotonic_remote_time >
1049 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001050 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001051 << "Check failed: timestamped_message.monotonic_remote_time < "
1052 "state->monotonic_remote_now(timestamped_message.channel_"
1053 "index) ("
1054 << timestamped_message.monotonic_remote_time << " vs. "
1055 << state->monotonic_remote_now(
1056 timestamped_message.channel_index)
1057 << ") " << state->event_loop()->node()->name()->string_view()
1058 << " to "
1059 << state->remote_node(timestamped_message.channel_index)
1060 ->name()
1061 ->string_view()
1062 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001063 << " ("
1064 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001065 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001066 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001067 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001068 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001069 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001070 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001071 << ") " << state->DebugString();
1072 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001073 }
1074
Austin Schuh15649d62019-12-28 16:36:38 -08001075 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001076 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001077 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001078
Austin Schuh2f8fd752020-09-01 22:38:28 -07001079 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001080 << timestamped_message.monotonic_event_time << " "
1081 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001082 // TODO(austin): std::move channel_data in and make that efficient in
1083 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001084 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001085 } else if (state->found_last_message() ||
1086 (!ignore_missing_data_ &&
1087 // When starting up, we can have data which was sent before
1088 // the log starts, but the timestamp was after the log
1089 // starts. This is unreasonable to avoid, so ignore the
1090 // missing data.
1091 timestamped_message.monotonic_remote_time.time >=
1092 state->monotonic_remote_start_time(
1093 timestamped_message.monotonic_remote_time.boot,
1094 timestamped_message.channel_index) &&
1095 !FLAGS_skip_missing_forwarding_entries)) {
1096 if (!state->found_last_message()) {
1097 // We've found a timestamp without data that we expect to have data
1098 // for. This likely means that we are at the end of the log file.
1099 // Record it and CHECK that in the rest of the log file, we don't find
1100 // any more data on that channel. Not all channels will end at the
1101 // same point in time since they can be in different files.
1102 VLOG(1) << "Found the last message on channel "
1103 << timestamped_message.channel_index << ", "
1104 << configuration::CleanedChannelToString(
1105 logged_configuration()->channels()->Get(
1106 timestamped_message.channel_index))
1107 << " on node " << MaybeNodeName(state->event_loop()->node())
1108 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001109
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001110 // The user might be working with log files from 1 node but forgot to
1111 // configure the infrastructure to log data for a remote channel on
1112 // that node. That can be very hard to debug, even though the log
1113 // reader is doing the right thing. At least log a warning in that
1114 // case and tell the user what is happening so they can either update
1115 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001116 const std::vector<std::string> logger_nodes =
1117 FindLoggerNodes(log_files_);
1118 if (logger_nodes.size()) {
1119 // We have old logs which don't have the logger nodes logged. In
1120 // that case, we can't be helpful :(
1121 bool data_logged = false;
1122 const Channel *channel = logged_configuration()->channels()->Get(
1123 timestamped_message.channel_index);
1124 for (const std::string &node : logger_nodes) {
1125 data_logged |=
1126 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1127 }
1128 if (!data_logged) {
1129 LOG(WARNING) << "Got a timestamp without any logfiles which "
1130 "could contain data for channel "
1131 << configuration::CleanedChannelToString(channel);
1132 LOG(WARNING) << "Only have logs logged on ["
1133 << absl::StrJoin(logger_nodes, ", ") << "]";
1134 LOG(WARNING)
1135 << "Dropping the rest of the data on "
1136 << state->event_loop()->node()->name()->string_view();
1137 LOG(WARNING)
1138 << "Consider using --skip_missing_forwarding_entries to "
1139 "bypass this, update your config to log it, or add data "
1140 "from one of the nodes it is logged on.";
1141 }
1142 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001143 // Now that we found the end of one channel, artificially stop the
1144 // rest by setting the found_last_message bit. It is confusing when
1145 // part of your data gets replayed but not all. The rest of them will
1146 // get dropped as they are replayed to keep memory usage down.
1147 state->SetFoundLastMessage(true);
1148
1149 // Vector storing if we've seen a nullptr message or not per channel.
1150 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001151 }
1152
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001153 // Make sure that once we have seen the last message on a channel,
1154 // data doesn't start back up again. If the user wants to play
1155 // through events like this, they can set
1156 // --skip_missing_forwarding_entries or ignore_missing_data_.
1157 if (timestamped_message.data == nullptr) {
1158 state->set_last_message(timestamped_message.channel_index);
1159 } else {
1160 if (state->last_message(timestamped_message.channel_index)) {
1161 LOG(FATAL) << "Found missing data in the middle of the log file on "
1162 "channel "
1163 << timestamped_message.channel_index << " "
1164 << configuration::StrippedChannelToString(
1165 logged_configuration()->channels()->Get(
1166 timestamped_message.channel_index))
1167 << " " << timestamped_message << " "
1168 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001169 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001170 }
Austin Schuh92547522019-12-28 14:33:43 -08001171 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001172 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001173 LOG(WARNING)
1174 << "Not sending data from before the start of the log file. "
1175 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1176 .count()
1177 << " start "
1178 << monotonic_start_time(state->node()).time_since_epoch().count()
1179 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001180 }
1181
James Kuszmaula16a7912022-06-17 10:58:12 -07001182 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001183 if (next_time != BootTimestamp::max_time()) {
1184 if (next_time.boot != state->boot_count()) {
1185 VLOG(1) << "Next message for "
1186 << MaybeNodeName(state->event_loop()->node())
1187 << "is on the next boot, " << next_time << " now is "
1188 << state->monotonic_now();
1189 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001190 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001191 return;
1192 }
James Kuszmaul09632422022-05-25 15:56:19 -07001193 if (event_loop_factory_ != nullptr) {
1194 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1195 << "wakeup for " << next_time.time << "("
1196 << state->ToDistributedClock(next_time.time)
1197 << " distributed), now is " << state->monotonic_now();
1198 } else {
1199 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1200 << "wakeup for " << next_time.time << ", now is "
1201 << state->monotonic_now();
1202 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001203 // TODO(james): This can result in negative times getting passed-through
1204 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001205 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001206 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001207 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1208 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001209 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001210 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001211 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001212 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001213 // Doesn't apply to single-EventLoop replay since the watchers in question
1214 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001215 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001216 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1217 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001218 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001219 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001220
Austin Schuh2f8fd752020-09-01 22:38:28 -07001221 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1222 << state->event_loop()->context().monotonic_event_time << " now "
1223 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001224 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001225
James Kuszmaula16a7912022-06-17 10:58:12 -07001226 state->SeedSortedMessages();
1227
1228 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001229 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001230 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1231 if (start_time_ != realtime_clock::min_time) {
1232 state->SetStartTimeFlag(start_time_);
1233 }
1234 if (end_time_ != realtime_clock::max_time) {
1235 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001236 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001237 }
Austin Schuh58646e22021-08-23 23:51:46 -07001238 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001239 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001240 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001241 // Queue up messages and then set clock offsets (we don't want to set
1242 // clock offsets before we've done the work of getting the first messages
1243 // primed).
1244 state->QueueThreadUntil(
1245 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1246 std::chrono::duration<double>(
1247 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001248 state->MaybeSetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001249 state->Setup(next_time.time);
1250 state->SetupStartupTimer();
1251 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001252 }
1253}
1254
Austin Schuhe33c08d2022-02-03 18:15:21 -08001255void LogReader::SetEndTime(std::string end_time) {
1256 if (end_time.empty()) {
1257 SetEndTime(realtime_clock::max_time);
1258 } else {
1259 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1260 aos::realtime_clock::FromString(end_time);
1261 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1262 << "'. Expected a date in the format of "
1263 "2021-01-15_15-30-35.000000000.";
1264 SetEndTime(*parsed_end_time);
1265 }
1266}
1267
1268void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1269 end_time_ = end_time;
1270}
1271
1272void LogReader::SetStartTime(std::string start_time) {
1273 if (start_time.empty()) {
1274 SetStartTime(realtime_clock::min_time);
1275 } else {
1276 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1277 aos::realtime_clock::FromString(start_time);
1278 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1279 << "'. Expected a date in the format of "
1280 "2021-01-15_15-30-35.000000000.";
1281 SetStartTime(*parsed_start_time);
1282 }
1283}
1284
1285void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1286 start_time_ = start_time;
1287}
1288
Austin Schuhe309d2a2019-11-29 13:25:21 -08001289void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001290 // Make sure that things get destroyed in the correct order, rather than
1291 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001292 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001293 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001294 }
Austin Schuh92547522019-12-28 14:33:43 -08001295
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001296 event_loop_factory_unique_ptr_.reset();
1297 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001298}
1299
James Kuszmaul53da7f32022-09-11 11:11:55 -07001300namespace {
1301// Checks if the specified channel name/type exists in the config and, depending
1302// on the value of conflict_handling, calls conflict_handler or just dies.
1303template <typename F>
1304void CheckAndHandleRemapConflict(std::string_view new_name,
1305 std::string_view new_type,
1306 const Configuration *config,
1307 LogReader::RemapConflict conflict_handling,
1308 F conflict_handler) {
1309 const Channel *existing_channel =
1310 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1311 if (existing_channel != nullptr) {
1312 switch (conflict_handling) {
1313 case LogReader::RemapConflict::kDisallow:
1314 LOG(FATAL)
1315 << "Channel "
1316 << configuration::StrippedChannelToString(existing_channel)
1317 << " is already used--you can't remap a logged channel to it.";
1318 break;
1319 case LogReader::RemapConflict::kCascade:
1320 LOG(INFO) << "Automatically remapping "
1321 << configuration::StrippedChannelToString(existing_channel)
1322 << " to avoid conflicts.";
1323 conflict_handler();
1324 break;
1325 }
1326 }
1327}
1328} // namespace
1329
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001330void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001331 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001332 std::string_view new_type,
1333 RemapConflict conflict_handling) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001334 if (replay_channels_ != nullptr) {
1335 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1336 std::make_pair(name, type)) != replay_channels_->end())
1337 << "Attempted to remap channel " << name << " " << type
1338 << " which is not included in the replay channels passed to LogReader.";
1339 }
1340
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001341 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1342 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1343 if (channel->name()->str() == name &&
1344 channel->type()->string_view() == type) {
1345 CHECK_EQ(0u, remapped_channels_.count(ii))
1346 << "Already remapped channel "
1347 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001348 RemappedChannel remapped_channel;
1349 remapped_channel.remapped_name =
1350 std::string(add_prefix) + std::string(name);
1351 remapped_channel.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001352 const std::string_view remapped_type =
1353 remapped_channel.new_type.empty() ? type : remapped_channel.new_type;
1354 CheckAndHandleRemapConflict(
1355 remapped_channel.remapped_name, remapped_type,
1356 remapped_configuration_, conflict_handling,
1357 [this, &remapped_channel, remapped_type, add_prefix,
1358 conflict_handling]() {
1359 RemapLoggedChannel(remapped_channel.remapped_name, remapped_type,
1360 add_prefix, "", conflict_handling);
1361 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001362 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001363 VLOG(1) << "Remapping channel "
1364 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001365 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001366 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001367 return;
1368 }
1369 }
1370 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1371 << type;
1372}
1373
Austin Schuh01b4c352020-09-21 23:09:39 -07001374void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1375 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001376 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001377 std::string_view new_type,
1378 RemapConflict conflict_handling) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001379 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1380 const Channel *remapped_channel =
1381 configuration::GetChannel(logged_configuration(), name, type, "", node);
1382 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1383 << "\", \"type\": \"" << type << "\"}";
1384 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1385 << "\"}";
1386 VLOG(1) << "Remapped "
1387 << aos::configuration::StrippedChannelToString(remapped_channel);
1388
1389 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1390 // we want it to degrade if the heuristics fail to just work.
1391 //
1392 // The easiest way to do this is going to be incredibly specific and verbose.
1393 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1394 // /original/0/spray. Then, create a map from /original/spray to
1395 // /original/0/spray for just the type we were asked for.
1396 if (name != remapped_channel->name()->string_view()) {
1397 MapT new_map;
1398 new_map.match = std::make_unique<ChannelT>();
1399 new_map.match->name = absl::StrCat(add_prefix, name);
1400 new_map.match->type = type;
1401 if (node != nullptr) {
1402 new_map.match->source_node = node->name()->str();
1403 }
1404 new_map.rename = std::make_unique<ChannelT>();
1405 new_map.rename->name =
1406 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1407 maps_.emplace_back(std::move(new_map));
1408 }
1409
1410 const size_t channel_index =
1411 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1412 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1413 << "Already remapped channel "
1414 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001415
1416 RemappedChannel remapped_channel_struct;
1417 remapped_channel_struct.remapped_name =
1418 std::string(add_prefix) +
1419 std::string(remapped_channel->name()->string_view());
1420 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001421 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1422 CheckAndHandleRemapConflict(
1423 remapped_channel_struct.remapped_name, remapped_type,
1424 remapped_configuration_, conflict_handling,
1425 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1426 conflict_handling]() {
1427 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1428 node, add_prefix, "", conflict_handling);
1429 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001430 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001431 MakeRemappedConfig();
1432}
1433
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001434void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001435 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001436 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001437 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001438 << ": Can't change the mapping after the events are scheduled.";
1439 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001440 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001441
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001442 // If no remapping occurred and we are using the original config, then there
1443 // is nothing interesting to do here.
1444 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001445 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001446 return;
1447 }
1448 // Config to copy Channel definitions from. Use the specified
1449 // replay_configuration_ if it has been provided.
1450 const Configuration *const base_config = replay_configuration_ == nullptr
1451 ? logged_configuration()
1452 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001453
1454 // Create a config with all the channels, but un-sorted/merged. Collect up
1455 // the schemas while we do this. Call MergeConfiguration to sort everything,
1456 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001457
1458 // This is the builder that we use for the config containing all the new
1459 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001460 flatbuffers::FlatBufferBuilder fbb;
1461 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001462 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001463
1464 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1465 << ": Merging logic needs to be updated when the number of channel "
1466 "fields changes.";
1467
1468 // List of schemas.
1469 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1470 // Make sure our new RemoteMessage schema is in there for old logs without it.
1471 schema_map.insert(std::make_pair(
1472 RemoteMessage::GetFullyQualifiedName(),
1473 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1474 message_bridge::RemoteMessageSchema()))));
1475
1476 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001477 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001478 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001479 base_config, logged_configuration()->channels()->Get(pair.first), "",
1480 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001481 channel_offsets.emplace_back(
1482 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001483
1484 if (c->has_destination_nodes()) {
1485 for (const Connection *connection : *c->destination_nodes()) {
1486 switch (connection->timestamp_logger()) {
1487 case LoggerConfig::LOCAL_LOGGER:
1488 case LoggerConfig::NOT_LOGGED:
1489 // There is no timestamp channel associated with this, so ignore it.
1490 break;
1491
1492 case LoggerConfig::REMOTE_LOGGER:
1493 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1494 // We want to make a split timestamp channel regardless of what type
1495 // of log this used to be. No sense propagating the single
1496 // timestamp channel.
1497
1498 CHECK(connection->has_timestamp_logger_nodes());
1499 for (const flatbuffers::String *timestamp_logger_node :
1500 *connection->timestamp_logger_nodes()) {
1501 const Node *node = configuration::GetNode(
1502 logged_configuration(), timestamp_logger_node->string_view());
1503 message_bridge::ChannelTimestampFinder finder(
1504 logged_configuration(), "log_reader", node);
1505
1506 // We are assuming here that all the maps are setup correctly to
1507 // handle arbitrary timestamps. Apply the maps for this node to
1508 // see what name this ends up with.
1509 std::string name = finder.SplitChannelName(
1510 pair.second.remapped_name, c->type()->str(), connection);
1511 std::string unmapped_name = name;
1512 configuration::HandleMaps(logged_configuration()->maps(), &name,
1513 "aos.message_bridge.RemoteMessage",
1514 node);
1515 CHECK_NE(name, unmapped_name)
1516 << ": Remote timestamp channel was not remapped, this is "
1517 "very fishy";
1518 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1519 fbb.CreateString(name);
1520 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1521 fbb.CreateString("aos.message_bridge.RemoteMessage");
1522 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1523 fbb.CreateString(timestamp_logger_node->string_view());
1524
1525 // Now, build a channel. Don't log it, 2 senders, and match the
1526 // source frequency.
1527 Channel::Builder channel_builder(fbb);
1528 channel_builder.add_name(channel_name_offset);
1529 channel_builder.add_type(channel_type_offset);
1530 channel_builder.add_source_node(source_node_offset);
1531 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1532 channel_builder.add_num_senders(2);
1533 if (c->has_frequency()) {
1534 channel_builder.add_frequency(c->frequency());
1535 }
1536 channel_offsets.emplace_back(channel_builder.Finish());
1537 }
1538 break;
1539 }
1540 }
1541 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001542 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001543
Austin Schuh0de30f32020-12-06 12:44:28 -08001544 // Now reconstruct the original channels, translating types as needed
1545 for (const Channel *c : *base_config->channels()) {
1546 // Search for a mapping channel.
1547 std::string_view new_type = "";
1548 for (auto &pair : remapped_channels_) {
1549 const Channel *const remapped_channel =
1550 logged_configuration()->channels()->Get(pair.first);
1551 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1552 remapped_channel->type()->string_view() == c->type()->string_view()) {
1553 new_type = pair.second.new_type;
1554 break;
1555 }
1556 }
1557
1558 // Copy everything over.
1559 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1560
1561 // Add the schema if it doesn't exist.
1562 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1563 CHECK(c->has_schema());
1564 schema_map.insert(std::make_pair(c->type()->string_view(),
1565 RecursiveCopyFlatBuffer(c->schema())));
1566 }
1567 }
1568
1569 // The MergeConfiguration API takes a vector, not a map. Convert.
1570 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1571 while (!schema_map.empty()) {
1572 schemas.emplace_back(std::move(schema_map.begin()->second));
1573 schema_map.erase(schema_map.begin());
1574 }
1575
1576 // Create the Configuration containing the new channels that we want to add.
1577 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1578 channels_offset =
1579 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1580
1581 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001582 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001583 if (base_config->maps()) {
1584 for (const Map *map : *base_config->maps()) {
1585 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1586 }
1587 }
1588
1589 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001590 for (const MapT &map : maps_) {
1591 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001592 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001593 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001594 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001595 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001596 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001597 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1598 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001599 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001600 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001601 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001602 match_builder.add_name(match_name_offset);
1603 match_builder.add_type(match_type_offset);
1604 if (!map.match->source_node.empty()) {
1605 match_builder.add_source_node(match_source_node_offset);
1606 }
1607 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1608
Austin Schuh0de30f32020-12-06 12:44:28 -08001609 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001610 rename_builder.add_name(rename_name_offset);
1611 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1612
Austin Schuh0de30f32020-12-06 12:44:28 -08001613 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001614 map_builder.add_match(match_offset);
1615 map_builder.add_rename(rename_offset);
1616 map_offsets.emplace_back(map_builder.Finish());
1617 }
1618
Austin Schuh0de30f32020-12-06 12:44:28 -08001619 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1620 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001621
Austin Schuh0de30f32020-12-06 12:44:28 -08001622 // And copy everything else over.
1623 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1624 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1625
1626 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1627 applications_offset =
1628 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1629
1630 // Now insert everything else in unmodified.
1631 ConfigurationBuilder configuration_builder(fbb);
1632 if (!channels_offset.IsNull()) {
1633 configuration_builder.add_channels(channels_offset);
1634 }
1635 if (!maps_offsets.IsNull()) {
1636 configuration_builder.add_maps(maps_offsets);
1637 }
1638 if (!nodes_offset.IsNull()) {
1639 configuration_builder.add_nodes(nodes_offset);
1640 }
1641 if (!applications_offset.IsNull()) {
1642 configuration_builder.add_applications(applications_offset);
1643 }
1644
1645 if (base_config->has_channel_storage_duration()) {
1646 configuration_builder.add_channel_storage_duration(
1647 base_config->channel_storage_duration());
1648 }
1649
1650 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1651 << ": Merging logic needs to be updated when the number of configuration "
1652 "fields changes.";
1653
1654 fbb.Finish(configuration_builder.Finish());
1655
1656 // Clean it up and return it! By using MergeConfiguration here, we'll
1657 // actually get a deduplicated config for free too.
1658 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1659 configuration::MergeConfiguration(
1660 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1661
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001662 remapped_configuration_buffer_ =
1663 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001664 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001665
1666 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001667
1668 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001669}
1670
Naman Guptacf6d4422023-03-01 11:41:00 -08001671std::unique_ptr<const ReplayChannelIndices>
1672LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001673 if (replay_channels_ == nullptr) {
1674 return nullptr;
1675 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001676 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1677 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001678 for (auto const &channel : *replay_channels_) {
1679 const Channel *ch = configuration::GetChannel(
1680 logged_configuration(), channel.first, channel.second, "", node);
1681 if (ch == nullptr) {
1682 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1683 << " not found in configuration for node: "
1684 << node->name()->string_view() << " Skipping ...";
1685 continue;
1686 }
1687 const size_t channel_index =
1688 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001689 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001690 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001691 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1692 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001693 }
1694}
1695
Austin Schuh1c227352021-09-17 12:53:54 -07001696std::vector<const Channel *> LogReader::RemappedChannels() const {
1697 std::vector<const Channel *> result;
1698 result.reserve(remapped_channels_.size());
1699 for (auto &pair : remapped_channels_) {
1700 const Channel *const logged_channel =
1701 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1702
1703 auto channel_iterator = std::lower_bound(
1704 remapped_configuration_->channels()->cbegin(),
1705 remapped_configuration_->channels()->cend(),
1706 std::make_pair(std::string_view(pair.second.remapped_name),
1707 logged_channel->type()->string_view()),
1708 CompareChannels);
1709
1710 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1711 CHECK(EqualsChannels(
1712 *channel_iterator,
1713 std::make_pair(std::string_view(pair.second.remapped_name),
1714 logged_channel->type()->string_view())));
1715 result.push_back(*channel_iterator);
1716 }
1717 return result;
1718}
1719
Austin Schuh6f3babe2020-01-26 20:34:50 -08001720const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001721 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001722 const Channel *channel) {
1723 std::string_view channel_name = channel->name()->string_view();
1724 std::string_view channel_type = channel->type()->string_view();
1725 const int channel_index =
1726 configuration::ChannelIndex(logged_configuration(), channel);
1727 // If the channel is remapped, find the correct channel name to use.
1728 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001729 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001730 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001731 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001732 }
1733
Austin Schuhee711052020-08-24 16:06:09 -07001734 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001735 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001736 configuration(), channel_name, channel_type,
1737 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001738
1739 CHECK(remapped_channel != nullptr)
1740 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1741 << channel_type << "\"} because it is not in the provided configuration.";
1742
1743 return remapped_channel;
1744}
1745
James Kuszmaul09632422022-05-25 15:56:19 -07001746LogReader::State::State(
1747 std::unique_ptr<TimestampMapper> timestamp_mapper,
1748 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001749 std::function<void()> notice_realtime_end, const Node *node,
1750 LogReader::State::ThreadedBuffering threading,
Naman Guptacf6d4422023-03-01 11:41:00 -08001751 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices)
James Kuszmaul09632422022-05-25 15:56:19 -07001752 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001753 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001754 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001755 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001756 threading_(threading),
Naman Guptacf6d4422023-03-01 11:41:00 -08001757 replay_channel_indices_(std::move(replay_channel_indices)) {
1758 if (replay_channel_indices_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001759 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001760 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001761 const TimestampedMessage &message) -> bool {
1762 auto const begin = filter->cbegin();
1763 auto const end = filter->cend();
1764 // TODO: benchmark strategies for channel_index matching
1765 return std::binary_search(begin, end, message.channel_index);
1766 });
1767 }
1768}
Austin Schuh287d43d2020-12-04 20:19:33 -08001769
1770void LogReader::State::AddPeer(State *peer) {
1771 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1772 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1773 }
1774}
Austin Schuh858c9f32020-08-31 16:56:12 -07001775
Austin Schuh58646e22021-08-23 23:51:46 -07001776void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001777 NodeEventLoopFactory *node_event_loop_factory,
1778 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001779 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001780 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001781}
1782
1783void LogReader::State::SetChannelCount(size_t count) {
1784 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001785 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001786 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001787 channel_source_state_.resize(count);
1788 factory_channel_index_.resize(count);
1789 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001790}
1791
Austin Schuh58646e22021-08-23 23:51:46 -07001792void LogReader::State::SetRemoteTimestampSender(
1793 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1794 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1795}
1796
Austin Schuh858c9f32020-08-31 16:56:12 -07001797void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001798 size_t logged_channel_index, size_t factory_channel_index,
1799 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001800 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1801 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001802 channels_[logged_channel_index] = std::move(sender);
1803 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001804 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001805
Austin Schuh58646e22021-08-23 23:51:46 -07001806 if (is_forwarded) {
1807 queue_index_map_[logged_channel_index] =
1808 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001809 }
1810
1811 factory_channel_index_[logged_channel_index] = factory_channel_index;
1812}
1813
James Kuszmaula16a7912022-06-17 10:58:12 -07001814void LogReader::State::TrackMessageSendTiming(
1815 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1816 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1817 return;
1818 }
1819
1820 timing::MessageTimingT sample;
1821 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1822 sender.channel());
1823 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1824 sample.actual_send_time =
1825 sender.monotonic_sent_time().time_since_epoch().count();
1826 sample.send_time_error = aos::time::DurationInSeconds(
1827 expected_send_time - sender.monotonic_sent_time());
1828 send_timings_.push_back(sample);
1829
1830 // Somewhat arbitrarily send out timing information in batches of 100. No need
1831 // to create excessive overhead in regenerated logfiles.
1832 // TODO(james): The overhead may be fine.
1833 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1834 CHECK(timing_statistics_sender_.valid());
1835 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1836 SendMessageTimings();
1837 }
1838}
1839
1840void LogReader::State::SendMessageTimings() {
1841 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1842 return;
1843 }
1844 auto builder = timing_statistics_sender_.MakeBuilder();
1845 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1846 for (const auto &timing : send_timings_) {
1847 timing_offsets.push_back(
1848 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1849 }
1850 send_timings_.clear();
1851 flatbuffers::Offset<
1852 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1853 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1854 timing::ReplayTiming::Builder timing_builder =
1855 builder.MakeBuilder<timing::ReplayTiming>();
1856 timing_builder.add_messages(timings_offset);
1857 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1858}
1859
Austin Schuh287d43d2020-12-04 20:19:33 -08001860bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1861 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001862 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001863 uint32_t remote_queue_index = 0xffffffff;
1864
Austin Schuh287d43d2020-12-04 20:19:33 -08001865 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001866 State *source_state =
1867 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001868 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001869 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001870 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001871
Austin Schuh9942bae2021-01-07 22:06:44 -08001872 struct SentTimestamp {
1873 monotonic_clock::time_point monotonic_event_time;
1874 uint32_t queue_index;
1875 } search;
1876
Austin Schuh58646e22021-08-23 23:51:46 -07001877 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1878 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001879 search.monotonic_event_time =
1880 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001881 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001882
1883 // Find the sent time if available.
1884 auto element = std::lower_bound(
1885 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001886 [](ContiguousSentTimestamp a, SentTimestamp b) {
1887 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001888 return true;
1889 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001890 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001891 return false;
1892 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001893
1894 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001895 return true;
1896 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001897 if (a.starting_queue_index >= b.queue_index) {
1898 return false;
1899 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001900
Austin Schuh9942bae2021-01-07 22:06:44 -08001901 // If it isn't clearly below or above, it is below. Since we return
1902 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001903 return false;
1904 });
1905
1906 // TODO(austin): Be a bit more principled here, but we will want to do that
1907 // after the logger rewrite. We hit this when one node finishes, but the
1908 // other node isn't done yet. So there is no send time, but there is a
1909 // receive time.
1910 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001911 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1912 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001913
1914 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001915 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001916 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001917 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001918 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001919 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001920 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001921 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001922
Austin Schuh58646e22021-08-23 23:51:46 -07001923 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001924 element->actual_queue_index -
1925 element->starting_queue_index;
1926 } else {
1927 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001928 }
Austin Schuh58646e22021-08-23 23:51:46 -07001929 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1930 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001931 }
1932
James Kuszmaul09632422022-05-25 15:56:19 -07001933 if (event_loop_factory_ != nullptr &&
1934 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1935 multinode_filters_ != nullptr) {
1936 // Sanity check that we are using consistent boot uuids.
1937 State *source_state =
1938 channel_source_state_[timestamped_message.channel_index];
1939 CHECK_EQ(multinode_filters_->boot_uuid(
1940 configuration::GetNodeIndex(event_loop_->configuration(),
1941 source_state->node()),
1942 timestamped_message.monotonic_remote_time.boot),
1943 CHECK_NOTNULL(
1944 CHECK_NOTNULL(
1945 channel_source_state_[timestamped_message.channel_index])
1946 ->event_loop_)
1947 ->boot_uuid());
1948 }
1949
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001950 // Send! Use the replayed queue index here instead of the logged queue index
1951 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001952 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001953 RawSender::SharedSpan(timestamped_message.data,
1954 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001955 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001956 timestamped_message.realtime_remote_time, remote_queue_index,
1957 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001958 ? CHECK_NOTNULL(multinode_filters_)
1959 ->boot_uuid(configuration::GetNodeIndex(
1960 event_loop_->configuration(),
1961 channel_source_state_[timestamped_message
1962 .channel_index]
1963 ->node()),
1964 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001965 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001966 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001967 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1968 timestamped_message.monotonic_event_time.time) {
1969 // Only track errors for non-fetched messages.
1970 TrackMessageSendTiming(
1971 *sender,
1972 timestamped_message.monotonic_event_time.time + clock_offset());
1973 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001974
Austin Schuh287d43d2020-12-04 20:19:33 -08001975 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001976 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001977 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1978 // Nothing here, start a range with 0 length.
1979 ContiguousSentTimestamp timestamp;
1980 timestamp.starting_monotonic_event_time =
1981 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001982 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001983 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001984 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001985 timestamp.actual_queue_index = sender->sent_queue_index();
1986 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1987 timestamp);
1988 } else {
1989 // We've got something. See if the next timestamp is still contiguous. If
1990 // so, grow it.
1991 ContiguousSentTimestamp *back =
1992 &queue_index_map_[timestamped_message.channel_index]->back();
1993 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001994 (timestamped_message.queue_index.index -
1995 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001996 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001997 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001998 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001999 } else {
2000 // Otherwise, make a new one.
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 }
2011 }
2012
2013 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2014 // queue index diverge a couple of elements, which would be a very small
2015 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002016 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2017 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002018 // TODO(james): Currently, If running replay against a single event loop,
2019 // remote timestamps will not get replayed because this code-path only
2020 // gets triggered on the event loop that receives the forwarded message
2021 // that the timestamps correspond to. This code, as written, also doesn't
2022 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002023 State *source_state =
2024 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2025
Austin Schuh969cd602021-01-03 00:09:45 -08002026 flatbuffers::FlatBufferBuilder fbb;
2027 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002028 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2029 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002030
Austin Schuh969cd602021-01-03 00:09:45 -08002031 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002032
2033 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002034 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002035
2036 // Swap the remote and sent metrics. They are from the sender's
2037 // perspective, not the receiver's perspective.
2038 message_header_builder.add_monotonic_sent_time(
2039 sender->monotonic_sent_time().time_since_epoch().count());
2040 message_header_builder.add_realtime_sent_time(
2041 sender->realtime_sent_time().time_since_epoch().count());
2042 message_header_builder.add_queue_index(sender->sent_queue_index());
2043
Austin Schuh58646e22021-08-23 23:51:46 -07002044 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2045 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002046 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002047 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2048 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002049 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002050 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002051
2052 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002053 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002054
Austin Schuh969cd602021-01-03 00:09:45 -08002055 fbb.Finish(message_header_builder.Finish());
2056
2057 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2058 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002059 timestamped_message.monotonic_timestamp_time,
2060 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002061 }
2062
2063 return true;
2064}
2065
Austin Schuh969cd602021-01-03 00:09:45 -08002066LogReader::RemoteMessageSender::RemoteMessageSender(
2067 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2068 : event_loop_(event_loop),
2069 sender_(std::move(sender)),
2070 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2071
2072void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2073 if (remote_timestamps_.empty()) {
2074 CHECK_NOTNULL(timer_);
2075 timer_->Disable();
2076 scheduled_time_ = monotonic_clock::min_time;
2077 return;
2078 }
2079
2080 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2081 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002082 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002083 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002084 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2085 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002086 }
2087}
2088
2089void LogReader::RemoteMessageSender::Send(
2090 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002091 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002092 // There are 2 variants of logs.
2093 // 1) Logs without monotonic_timestamp_time
2094 // 2) Logs with monotonic_timestamp_time
2095 //
2096 // As of Jan 2021, we shouldn't have any more logs without
2097 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2098 // the effort of saving.
2099 //
2100 // This gives us 3 cases, 2 of which are undistinguishable.
2101 // 1) Old log without monotonic_timestamp_time.
2102 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2103 // remotely so we actually have monotonic_timestamp_time.
2104 // 3) New log, but the timestamp was logged on the node receiving the message
2105 // so there is no monotonic_timestamp_time.
2106 //
2107 // Our goal when replaying is to accurately reproduce the state of the world
2108 // present when logging. If a timestamp wasn't sent back across the network,
2109 // we shouldn't replay one back across the network.
2110 //
2111 // Given that we don't really care about 1, we can use the presence of the
2112 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2113 // monotonic_timestamp_time, this means the message was logged locally and
2114 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002115 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002116 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002117 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002118
Austin Schuh58646e22021-08-23 23:51:46 -07002119 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2120
Austin Schuhc41d6a82021-07-16 14:49:23 -07002121 remote_timestamps_.emplace(
2122 std::upper_bound(
2123 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002124 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002125 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2126 const Timestamp &timestamp) {
2127 return monotonic_timestamp_time <
2128 timestamp.monotonic_timestamp_time;
2129 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002130 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002131 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002132}
2133
2134void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002135 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2136 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002137 CHECK(!remote_timestamps_.empty());
2138
2139 // Send out all timestamps at the currently scheduled time.
2140 while (remote_timestamps_.front().monotonic_timestamp_time ==
2141 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002142 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2143 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002144 remote_timestamps_.pop_front();
2145 if (remote_timestamps_.empty()) {
2146 break;
2147 }
2148 }
2149 scheduled_time_ = monotonic_clock::min_time;
2150
2151 ScheduleTimestamp();
2152}
2153
2154LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002155 const Channel *channel, const Connection *connection) {
2156 message_bridge::ChannelTimestampFinder finder(event_loop_);
2157 // Look at any pre-created channel/connection pairs.
2158 {
2159 auto it =
2160 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2161 if (it != channel_timestamp_loggers_.end()) {
2162 return it->second.get();
2163 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002164 }
2165
Austin Schuh61e973f2021-02-21 21:43:56 -08002166 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2167 // to.
2168 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2169
2170 {
2171 // See if that has been created before. If so, cache it in
2172 // channel_timestamp_loggers_ and return.
2173 auto it = timestamp_loggers_.find(timestamp_channel);
2174 if (it != timestamp_loggers_.end()) {
2175 CHECK(channel_timestamp_loggers_
2176 .try_emplace(std::make_pair(channel, connection), it->second)
2177 .second);
2178 return it->second.get();
2179 }
2180 }
2181
2182 // Otherwise, make a sender, save it, and cache it.
2183 auto result = channel_timestamp_loggers_.try_emplace(
2184 std::make_pair(channel, connection),
2185 std::make_shared<RemoteMessageSender>(
2186 event_loop()->MakeSender<RemoteMessage>(
2187 timestamp_channel->name()->string_view()),
2188 event_loop()));
2189
2190 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2191 .second);
2192 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002193}
2194
Austin Schuhdda74ec2021-01-03 19:30:37 -08002195TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002196 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002197 if (message_queuer_.has_value()) {
2198 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2199 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2200 message_queuer_->SetState(
2201 message.value().monotonic_event_time +
2202 std::chrono::duration_cast<std::chrono::nanoseconds>(
2203 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2204 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002205 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002206 CHECK(timestamp_mapper_ != nullptr);
2207 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2208 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002209
James Kuszmaula16a7912022-06-17 10:58:12 -07002210 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002211
James Kuszmaula16a7912022-06-17 10:58:12 -07002212 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2213 << result.monotonic_event_time;
2214 timestamp_mapper_->PopFront();
2215 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002216
James Kuszmaula16a7912022-06-17 10:58:12 -07002217 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002218
James Kuszmaula16a7912022-06-17 10:58:12 -07002219 VLOG(1) << "Popped " << result
2220 << configuration::CleanedChannelToString(
2221 event_loop_->configuration()->channels()->Get(
2222 factory_channel_index_[result.channel_index]));
2223 return result;
2224 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002225}
2226
James Kuszmaula16a7912022-06-17 10:58:12 -07002227BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2228 if (!message_queuer_.has_value()) {
2229 return SingleThreadedOldestMessageTime();
2230 }
2231 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2232 if (!message.has_value()) {
2233 return BootTimestamp::max_time();
2234 }
2235 if (message.value().monotonic_event_time.boot == boot_count()) {
2236 ObserveNextMessage(message.value().monotonic_event_time.time,
2237 message.value().realtime_event_time);
2238 }
2239 return message.value().monotonic_event_time;
2240}
2241
2242BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2243 CHECK(!message_queuer_.has_value())
2244 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2245 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002246 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002247 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002248 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002249 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2250 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002251 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002252 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002253 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002254 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002255 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2256 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2257 result_ptr->realtime_event_time);
2258 }
Austin Schuh58646e22021-08-23 23:51:46 -07002259 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002260}
2261
2262void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002263 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002264
Austin Schuhe639ea12021-01-25 13:00:22 -08002265 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2266 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002267}
2268
2269void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002270 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002271 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002272 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002273 for (size_t i = 0; i < channels_.size(); ++i) {
2274 channels_[i].reset();
2275 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002276 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002277 channel_timestamp_loggers_.clear();
2278 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002279 event_loop_unique_ptr_.reset();
2280 event_loop_ = nullptr;
2281 timer_handler_ = nullptr;
2282 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002283 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002284}
2285
Austin Schuhe33c08d2022-02-03 18:15:21 -08002286void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2287 if (start_time != realtime_clock::min_time) {
2288 start_event_notifier_ = std::make_unique<EventNotifier>(
2289 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2290 }
2291}
2292
2293void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2294 if (end_time != realtime_clock::max_time) {
2295 end_event_notifier_ = std::make_unique<EventNotifier>(
2296 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2297 }
2298}
2299
2300void LogReader::State::ObserveNextMessage(
2301 monotonic_clock::time_point monotonic_event,
2302 realtime_clock::time_point realtime_event) {
2303 if (start_event_notifier_) {
2304 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2305 }
2306 if (end_event_notifier_) {
2307 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2308 }
2309}
2310
2311void LogReader::State::ClearTimeFlags() {
2312 start_event_notifier_.reset();
2313 end_event_notifier_.reset();
2314}
2315
2316void LogReader::State::NotifyLogfileStart() {
2317 if (start_event_notifier_) {
2318 if (start_event_notifier_->realtime_event_time() >
2319 realtime_start_time(boot_count())) {
2320 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2321 << " > " << realtime_start_time(boot_count());
2322 return;
2323 }
2324 }
2325 if (found_last_message_) {
2326 VLOG(1) << "Last message already found, bailing";
2327 return;
2328 }
2329 RunOnStart();
2330}
2331
2332void LogReader::State::NotifyFlagStart() {
2333 if (start_event_notifier_->realtime_event_time() >=
2334 realtime_start_time(boot_count())) {
2335 RunOnStart();
2336 }
2337}
2338
2339void LogReader::State::NotifyLogfileEnd() {
2340 if (found_last_message_) {
2341 return;
2342 }
2343
2344 if (!stopped_ && started_) {
2345 RunOnEnd();
2346 }
2347}
2348
2349void LogReader::State::NotifyFlagEnd() {
2350 if (!stopped_ && started_) {
2351 RunOnEnd();
2352 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002353 CHECK(notice_realtime_end_);
2354 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002355 }
2356}
2357
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002358void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002359 if (node_event_loop_factory_ == nullptr) {
2360 // If not running with simulated event loop, set the monotonic clock
2361 // offset.
2362 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2363
2364 if (start_event_notifier_) {
2365 start_event_notifier_->SetClockOffset(clock_offset_);
2366 }
2367 if (end_event_notifier_) {
2368 end_event_notifier_->SetClockOffset(clock_offset_);
2369 }
2370 }
2371}
2372
James Kuszmaulb67409b2022-06-20 16:25:03 -07002373void LogReader::SetRealtimeReplayRate(double replay_rate) {
2374 CHECK(event_loop_factory_ != nullptr)
2375 << ": Can't set replay rate without an event loop factory (have you "
2376 "called Register()?).";
2377 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2378}
2379
James Kuszmaulb11a1502022-07-01 16:02:25 -07002380void LogReader::NoticeRealtimeEnd() {
2381 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2382 --live_nodes_with_realtime_time_end_;
2383 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2384 event_loop_factory_ != nullptr) {
2385 event_loop_factory_->Exit();
2386 }
2387}
2388
Austin Schuhe309d2a2019-11-29 13:25:21 -08002389} // namespace logger
2390} // namespace aos