blob: b078d184a12f832ff7fde7b97b64d6e3b98bb197 [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
Austin Schuhaf8a0d32023-05-03 09:53:06 -07003#include <dirent.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08004#include <fcntl.h>
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08008
Tyler Chatowbf0609c2021-07-31 16:13:27 -07009#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -080010#include <vector>
11
Austin Schuh2f8fd752020-09-01 22:38:28 -070012#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080013#include "absl/types/span.h"
14#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070015#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070016#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080017#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080018#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070019#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080020#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080021#include "aos/network/remote_message_generated.h"
22#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080023#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080024#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080025#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070026#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070027#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080029#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080030
Austin Schuh15649d62019-12-28 16:36:38 -080031DEFINE_bool(skip_missing_forwarding_entries, false,
32 "If true, drop any forwarding entries with missing data. If "
33 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080034
Austin Schuh0ca1fd32020-12-18 22:53:05 -080035DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080036
Austin Schuh2f8fd752020-09-01 22:38:28 -070037DEFINE_bool(skip_order_validation, false,
38 "If true, ignore any out of orderness in replay");
39
Austin Schuhf0688662020-12-19 15:37:45 -080040DEFINE_double(
41 time_estimation_buffer_seconds, 2.0,
42 "The time to buffer ahead in the log file to accurately reconstruct time.");
43
Austin Schuhe33c08d2022-02-03 18:15:21 -080044DEFINE_string(
45 start_time, "",
46 "If set, start at this point in time in the log on the realtime clock.");
47DEFINE_string(
48 end_time, "",
49 "If set, end at this point in time in the log on the realtime clock.");
50
James Kuszmaul09632422022-05-25 15:56:19 -070051DEFINE_bool(drop_realtime_messages_before_start, false,
52 "If set, will drop any messages sent before the start of the "
53 "logfile in realtime replay. Setting this guarantees consistency "
54 "in timing with the original logfile, but means that you lose "
55 "access to fetched low-frequency messages.");
56
James Kuszmaula16a7912022-06-17 10:58:12 -070057DEFINE_double(
58 threaded_look_ahead_seconds, 2.0,
59 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
60 "Can validly be zero, but higher values are encouraged for realtime replay "
61 "in order to prevent the replay from ever having to block on waiting for "
62 "the reader to find the next message.");
63
Austin Schuhe309d2a2019-11-29 13:25:21 -080064namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070065namespace configuration {
66// We don't really want to expose this publicly, but log reader doesn't really
67// want to re-implement it.
68void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
69 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070070} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080071namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070072namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080073
Austin Schuh1c227352021-09-17 12:53:54 -070074bool CompareChannels(const Channel *c,
75 ::std::pair<std::string_view, std::string_view> p) {
76 int name_compare = c->name()->string_view().compare(p.first);
77 if (name_compare == 0) {
78 return c->type()->string_view() < p.second;
79 } else if (name_compare < 0) {
80 return true;
81 } else {
82 return false;
83 }
84}
85
86bool EqualsChannels(const Channel *c,
87 ::std::pair<std::string_view, std::string_view> p) {
88 return c->name()->string_view() == p.first &&
89 c->type()->string_view() == p.second;
90}
91
Austin Schuh0de30f32020-12-06 12:44:28 -080092// Copies the channel, removing the schema as we go. If new_name is provided,
93// it is used instead of the name inside the channel. If new_type is provided,
94// it is used instead of the type in the channel.
95flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
96 std::string_view new_name,
97 std::string_view new_type,
98 flatbuffers::FlatBufferBuilder *fbb) {
99 flatbuffers::Offset<flatbuffers::String> name_offset =
100 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
101 : new_name);
102 flatbuffers::Offset<flatbuffers::String> type_offset =
103 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
104 flatbuffers::Offset<flatbuffers::String> source_node_offset =
105 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
106 : 0;
107
108 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
109 destination_nodes_offset =
110 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
111
112 flatbuffers::Offset<
113 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
114 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
115
116 Channel::Builder channel_builder(*fbb);
117 channel_builder.add_name(name_offset);
118 channel_builder.add_type(type_offset);
119 if (c->has_frequency()) {
120 channel_builder.add_frequency(c->frequency());
121 }
122 if (c->has_max_size()) {
123 channel_builder.add_max_size(c->max_size());
124 }
125 if (c->has_num_senders()) {
126 channel_builder.add_num_senders(c->num_senders());
127 }
128 if (c->has_num_watchers()) {
129 channel_builder.add_num_watchers(c->num_watchers());
130 }
131 if (!source_node_offset.IsNull()) {
132 channel_builder.add_source_node(source_node_offset);
133 }
134 if (!destination_nodes_offset.IsNull()) {
135 channel_builder.add_destination_nodes(destination_nodes_offset);
136 }
137 if (c->has_logger()) {
138 channel_builder.add_logger(c->logger());
139 }
140 if (!logger_nodes_offset.IsNull()) {
141 channel_builder.add_logger_nodes(logger_nodes_offset);
142 }
143 if (c->has_read_method()) {
144 channel_builder.add_read_method(c->read_method());
145 }
146 if (c->has_num_readers()) {
147 channel_builder.add_num_readers(c->num_readers());
148 }
149 return channel_builder.Finish();
150}
151
Austin Schuhe309d2a2019-11-29 13:25:21 -0800152namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800153using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700154} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800155
Austin Schuhe33c08d2022-02-03 18:15:21 -0800156// Class to manage triggering events on the RT clock while replaying logs. Since
157// the RT clock can only change when we get a message, we only need to update
158// our timers when new messages are read.
159class EventNotifier {
160 public:
161 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
162 std::string_view name,
163 realtime_clock::time_point realtime_event_time)
164 : event_loop_(event_loop),
165 fn_(std::move(fn)),
166 realtime_event_time_(realtime_event_time) {
167 CHECK(event_loop_);
168 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
169
170 if (event_loop_->node() != nullptr) {
171 event_timer_->set_name(
172 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
173 } else {
174 event_timer_->set_name(name);
175 }
176 }
177
178 ~EventNotifier() { event_timer_->Disable(); }
179
James Kuszmaul09632422022-05-25 15:56:19 -0700180 // Sets the clock offset for realtime playback.
181 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
182 clock_offset_ = clock_offset;
183 }
184
Austin Schuhe33c08d2022-02-03 18:15:21 -0800185 // Returns the event trigger time.
186 realtime_clock::time_point realtime_event_time() const {
187 return realtime_event_time_;
188 }
189
190 // Observes the next message and potentially calls the callback or updates the
191 // timer.
192 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
193 realtime_clock::time_point realtime_message_time) {
194 if (realtime_message_time < realtime_event_time_) {
195 return;
196 }
197 if (called_) {
198 return;
199 }
200
201 // Move the callback wakeup time to the correct time (or make it now if
202 // there's a gap in time) now that we know it is before the next
203 // message.
204 const monotonic_clock::time_point candidate_monotonic =
205 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
206 const monotonic_clock::time_point monotonic_now =
207 event_loop_->monotonic_now();
208 if (candidate_monotonic < monotonic_now) {
209 // Whops, time went backwards. Just do it now.
210 HandleTime();
211 } else {
James Kuszmaul09632422022-05-25 15:56:19 -0700212 event_timer_->Setup(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800213 }
214 }
215
216 private:
217 void HandleTime() {
218 if (!called_) {
219 called_ = true;
220 fn_();
221 }
222 }
223
224 EventLoop *event_loop_ = nullptr;
225 TimerHandler *event_timer_ = nullptr;
226 std::function<void()> fn_;
227
228 const realtime_clock::time_point realtime_event_time_ =
229 realtime_clock::min_time;
230
James Kuszmaul09632422022-05-25 15:56:19 -0700231 std::chrono::nanoseconds clock_offset_{0};
232
Austin Schuhe33c08d2022-02-03 18:15:21 -0800233 bool called_ = false;
234};
235
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800236LogReader::LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700237 const Configuration *replay_configuration,
238 const ReplayChannels *replay_channels)
239 : LogReader(SortParts({std::string(filename)}), replay_configuration,
240 replay_channels) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800241
Austin Schuh287d43d2020-12-04 20:19:33 -0800242LogReader::LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700243 const Configuration *replay_configuration,
244 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800245 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700246 replay_configuration_(replay_configuration),
247 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800248 SetStartTime(FLAGS_start_time);
249 SetEndTime(FLAGS_end_time);
250
Austin Schuh0ca51f32020-12-25 21:51:45 -0800251 CHECK_GT(log_files_.size(), 0u);
252 {
253 // Validate that we have the same config everwhere. This will be true if
254 // all the parts were sorted together and the configs match.
255 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800256 for (const LogFile &log_file : log_files_) {
257 if (log_file.config.get() == nullptr) {
258 LOG(FATAL) << "Couldn't find a config in " << log_file;
259 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800260 if (config == nullptr) {
261 config = log_file.config.get();
262 } else {
263 CHECK_EQ(config, log_file.config.get());
264 }
265 }
266 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800267
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700268 if (replay_channels_ != nullptr) {
269 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
270 "no messages will get replayed.";
271 }
272
Austin Schuh6331ef92020-01-07 18:28:09 -0800273 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800274
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700275 // Remap all existing remote timestamp channels. They will be recreated, and
276 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700277 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800278 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
279 "log_reader", node);
280
281 absl::btree_set<std::string_view> remote_nodes;
282
283 for (const Channel *channel : *logged_configuration()->channels()) {
284 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
285 continue;
286 }
287 if (!channel->has_destination_nodes()) {
288 continue;
289 }
290 for (const Connection *connection : *channel->destination_nodes()) {
291 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
292 node)) {
293 // Start by seeing if the split timestamp channels are being used for
294 // this message. If so, remap them.
295 const Channel *timestamp_channel = configuration::GetChannel(
296 logged_configuration(),
297 finder.SplitChannelName(channel, connection),
298 RemoteMessage::GetFullyQualifiedName(), "", node, true);
299
300 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700301 // If for some reason a timestamp channel is not NOT_LOGGED (which
302 // is unusual), then remap the channel so that the replayed channel
303 // doesn't overlap with the special separate replay we do for
304 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800305 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
306 RemapLoggedChannel<RemoteMessage>(
307 timestamp_channel->name()->string_view(), node);
308 }
309 continue;
310 }
311
312 // Otherwise collect this one up as a node to look for a combined
313 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700314 LOG(WARNING) << "Failed to find channel "
315 << finder.SplitChannelName(channel, connection)
316 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800317 remote_nodes.insert(connection->name()->string_view());
318 }
319 }
320 }
321
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700322 std::vector<const Node *> timestamp_logger_nodes =
323 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800324 for (const std::string_view remote_node : remote_nodes) {
325 const std::string channel = finder.CombinedChannelName(remote_node);
326
Austin Schuh0de30f32020-12-06 12:44:28 -0800327 // See if the log file is an old log with MessageHeader channels in it, or
328 // a newer log with RemoteMessage. If we find an older log, rename the
329 // type too along with the name.
330 if (HasChannel<MessageHeader>(channel, node)) {
331 CHECK(!HasChannel<RemoteMessage>(channel, node))
332 << ": Can't have both a MessageHeader and RemoteMessage remote "
333 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800334 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
335 // careful about updating the config, but there are fewer and fewer logs
336 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800337 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
338 "aos.message_bridge.RemoteMessage");
339 } else {
340 CHECK(HasChannel<RemoteMessage>(channel, node))
341 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
342 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
343 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800344 // Only bother to remap if there's something on the channel. We can
345 // tell if the channel was marked NOT_LOGGED or not. This makes the
346 // config not change un-necesarily when we replay a log with NOT_LOGGED
347 // messages.
348 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
349 RemapLoggedChannel<RemoteMessage>(channel, node);
350 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800351 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700352 }
353 }
354
Austin Schuh6aa77be2020-02-22 21:06:40 -0800355 if (replay_configuration) {
356 CHECK_EQ(configuration::MultiNode(configuration()),
357 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 << ": Log file and replay config need to both be multi or single "
359 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800360 }
361
Austin Schuh6f3babe2020-01-26 20:34:50 -0800362 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700363 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800364 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800365 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700366 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800367 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700368 << ": Log file and replay config need to have matching nodes "
369 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700370 for (const Node *node : *logged_configuration()->nodes()) {
371 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700372 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
373 << " in logged config that is not present in the replay "
374 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700375 }
376 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800377 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800378 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800379 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800380}
381
Austin Schuh6aa77be2020-02-22 21:06:40 -0800382LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700383 if (event_loop_factory_unique_ptr_) {
384 Deregister();
385 } else if (event_loop_factory_ != nullptr) {
386 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
387 "is destroyed";
388 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700389 // Zero out some buffers. It's easy to do use-after-frees on these, so make
390 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700391 if (remapped_configuration_buffer_) {
392 remapped_configuration_buffer_->Wipe();
393 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800394}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800395
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800396const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800397 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800398}
399
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800400const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800401 return remapped_configuration_;
402}
403
Austin Schuh07676622021-01-21 18:59:17 -0800404std::vector<const Node *> LogReader::LoggedNodes() const {
405 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800406}
Austin Schuh15649d62019-12-28 16:36:38 -0800407
Austin Schuh11d43732020-09-21 17:28:30 -0700408monotonic_clock::time_point LogReader::monotonic_start_time(
409 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800410 State *state =
411 states_[configuration::GetNodeIndex(configuration(), node)].get();
412 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
413
Austin Schuhf665eb42022-02-03 18:26:25 -0800414 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800415}
416
Austin Schuh11d43732020-09-21 17:28:30 -0700417realtime_clock::time_point LogReader::realtime_start_time(
418 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800419 State *state =
420 states_[configuration::GetNodeIndex(configuration(), node)].get();
421 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
422
Austin Schuhf665eb42022-02-03 18:26:25 -0800423 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800424}
425
Austin Schuh58646e22021-08-23 23:51:46 -0700426void LogReader::OnStart(std::function<void()> fn) {
427 CHECK(!configuration::MultiNode(configuration()));
428 OnStart(nullptr, std::move(fn));
429}
430
431void LogReader::OnStart(const Node *node, std::function<void()> fn) {
432 const int node_index = configuration::GetNodeIndex(configuration(), node);
433 CHECK_GE(node_index, 0);
434 CHECK_LT(node_index, static_cast<int>(states_.size()));
435 State *state = states_[node_index].get();
436 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
437
438 state->OnStart(std::move(fn));
439}
440
James Kuszmaula16a7912022-06-17 10:58:12 -0700441void LogReader::State::QueueThreadUntil(BootTimestamp time) {
442 if (threading_ == ThreadedBuffering::kYes) {
443 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
444 message_queuer_.emplace(
445 [this](const BootTimestamp queue_until) {
446 // This will be called whenever anything prompts us for any state
447 // change; there may be wakeups that result in us not having any new
448 // data to push (even if we aren't done), in which case we will return
449 // nullopt but not done().
450 if (last_queued_message_.has_value() &&
451 queue_until < last_queued_message_) {
452 return util::ThreadedQueue<TimestampedMessage,
453 BootTimestamp>::PushResult{
454 std::nullopt, false,
455 last_queued_message_ == BootTimestamp::max_time()};
456 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700457
James Kuszmaula16a7912022-06-17 10:58:12 -0700458 TimestampedMessage *message = timestamp_mapper_->Front();
459 // Upon reaching the end of the log, exit.
460 if (message == nullptr) {
461 last_queued_message_ = BootTimestamp::max_time();
462 return util::ThreadedQueue<TimestampedMessage,
463 BootTimestamp>::PushResult{std::nullopt,
464 false, true};
465 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700466
James Kuszmaula16a7912022-06-17 10:58:12 -0700467 last_queued_message_ = message->monotonic_event_time;
468 const util::ThreadedQueue<TimestampedMessage,
469 BootTimestamp>::PushResult result{
470 *message, queue_until >= last_queued_message_, false};
471 timestamp_mapper_->PopFront();
472 SeedSortedMessages();
473 return result;
474 },
475 time);
476 // Spin until the first few seconds of messages are queued up so that we
477 // don't end up with delays/inconsistent timing during the first few seconds
478 // of replay.
479 message_queuer_->WaitForNoMoreWork();
480 }
481}
482
Austin Schuh58646e22021-08-23 23:51:46 -0700483void LogReader::State::OnStart(std::function<void()> fn) {
484 on_starts_.emplace_back(std::move(fn));
485}
486
487void LogReader::State::RunOnStart() {
488 SetRealtimeOffset(monotonic_start_time(boot_count()),
489 realtime_start_time(boot_count()));
490
491 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
492 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800493 auto fn = [this]() {
494 for (size_t i = 0; i < on_starts_.size(); ++i) {
495 on_starts_[i]();
496 }
497 };
498 if (event_loop_factory_) {
499 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
500 } else {
501 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700502 }
503 stopped_ = false;
504 started_ = true;
505}
506
507void LogReader::OnEnd(std::function<void()> fn) {
508 CHECK(!configuration::MultiNode(configuration()));
509 OnEnd(nullptr, std::move(fn));
510}
511
512void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
513 const int node_index = configuration::GetNodeIndex(configuration(), node);
514 CHECK_GE(node_index, 0);
515 CHECK_LT(node_index, static_cast<int>(states_.size()));
516 State *state = states_[node_index].get();
517 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
518
519 state->OnEnd(std::move(fn));
520}
521
522void LogReader::State::OnEnd(std::function<void()> fn) {
523 on_ends_.emplace_back(std::move(fn));
524}
525
526void LogReader::State::RunOnEnd() {
527 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
528 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800529 auto fn = [this]() {
530 for (size_t i = 0; i < on_ends_.size(); ++i) {
531 on_ends_[i]();
532 }
533 };
534 if (event_loop_factory_) {
535 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
536 } else {
537 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700538 }
539
540 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800541 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700542 if (message_queuer_.has_value()) {
543 message_queuer_->StopPushing();
544 }
Austin Schuh58646e22021-08-23 23:51:46 -0700545}
546
James Kuszmaul94ca5132022-07-19 09:11:08 -0700547std::vector<
548 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
549LogReader::State::NonExclusiveChannels() {
550 CHECK_NOTNULL(node_event_loop_factory_);
551 const aos::Configuration *config = node_event_loop_factory_->configuration();
552 std::vector<
553 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
554 result{// Timing reports can be sent by logged and replayed applications.
555 {aos::configuration::GetChannel(config, "/aos",
556 "aos.timing.Report", "", node_),
557 NodeEventLoopFactory::ExclusiveSenders::kNo},
558 // AOS_LOG may be used in the log and in replay.
559 {aos::configuration::GetChannel(
560 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
561 NodeEventLoopFactory::ExclusiveSenders::kNo}};
562 for (const Node *const node : configuration::GetNodes(config)) {
563 if (node == nullptr) {
564 break;
565 }
566 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
567 config,
568 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700569 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700570 // The old-style remote timestamp channel can be populated from any
571 // channel, simulated or replayed.
572 if (old_timestamp_channel != nullptr) {
573 result.push_back(std::make_pair(
574 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
575 }
576 }
577 // Remove any channels that weren't found due to not existing in the
578 // config.
579 for (size_t ii = 0; ii < result.size();) {
580 if (result[ii].first == nullptr) {
581 result.erase(result.begin() + ii);
582 } else {
583 ++ii;
584 }
585 }
586 return result;
587}
588
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800589void LogReader::Register() {
590 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800591 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800592 Register(event_loop_factory_unique_ptr_.get());
593}
594
Austin Schuh58646e22021-08-23 23:51:46 -0700595void LogReader::RegisterWithoutStarting(
596 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800597 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700598 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800599 filters_ =
600 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800601 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700602 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800603 chrono::duration_cast<chrono::nanoseconds>(
604 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800605
Austin Schuhe639ea12021-01-25 13:00:22 -0800606 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700607 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800608 const size_t node_index =
609 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800610 std::vector<LogParts> filtered_parts = FilterPartsForNode(
611 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800612
James Kuszmaula16a7912022-06-17 10:58:12 -0700613 // We don't run with threading on the buffering for simulated event loops
614 // because we haven't attempted to validate how the interactions beteen the
615 // buffering and the timestamp mapper works when running multiple nodes
616 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800617 states_[node_index] = std::make_unique<State>(
618 filtered_parts.size() == 0u
619 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700620 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700621 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800622 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node));
Austin Schuh8bd96322020-02-13 21:18:22 -0800623 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700624 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800625 event_loop_factory_->GetNodeEventLoopFactory(node),
626 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700627
628 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800629 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800630 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800631 filters_->SetTimestampMappers(std::move(timestamp_mappers));
632
633 // Note: this needs to be set before any times are pulled, or we won't observe
634 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800635 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700636
Austin Schuh287d43d2020-12-04 20:19:33 -0800637 for (const Node *node : configuration::GetNodes(configuration())) {
638 const size_t node_index =
639 configuration::GetNodeIndex(configuration(), node);
640 State *state = states_[node_index].get();
641 for (const Node *other_node : configuration::GetNodes(configuration())) {
642 const size_t other_node_index =
643 configuration::GetNodeIndex(configuration(), other_node);
644 State *other_state = states_[other_node_index].get();
645 if (other_state != state) {
646 state->AddPeer(other_state);
647 }
648 }
649 }
650
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700651 // Register after making all the State objects so we can build references
652 // between them.
653 for (const Node *node : configuration::GetNodes(configuration())) {
654 const size_t node_index =
655 configuration::GetNodeIndex(configuration(), node);
656 State *state = states_[node_index].get();
657
Austin Schuh58646e22021-08-23 23:51:46 -0700658 // If we didn't find any log files with data in them, we won't ever get a
659 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700660 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700661 continue;
662 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700663
Austin Schuh58646e22021-08-23 23:51:46 -0700664 ++live_nodes_;
665
666 NodeEventLoopFactory *node_factory =
667 event_loop_factory_->GetNodeEventLoopFactory(node);
668 node_factory->OnStartup([this, state, node]() {
669 RegisterDuringStartup(state->MakeEventLoop(), node);
670 });
671 node_factory->OnShutdown([this, state, node]() {
672 RegisterDuringStartup(nullptr, node);
673 state->DestroyEventLoop();
674 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700675 }
676
James Kuszmaul46d82582020-05-09 19:50:09 -0700677 if (live_nodes_ == 0) {
678 LOG(FATAL)
679 << "Don't have logs from any of the nodes in the replay config--are "
680 "you sure that the replay config matches the original config?";
681 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800682
Austin Schuh87dd3832021-01-01 23:07:31 -0800683 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800684
Austin Schuh858c9f32020-08-31 16:56:12 -0700685 for (std::unique_ptr<State> &state : states_) {
686 state->SeedSortedMessages();
687 }
688
Austin Schuh6f3babe2020-01-26 20:34:50 -0800689 // Forwarding is tracked per channel. If it is enabled, we want to turn it
690 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700691 // nodes, and also replayed on the other nodes. This may not satisfy all
692 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800693 if (configuration::MultiNode(event_loop_factory_->configuration())) {
694 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
695 const Channel *channel = logged_configuration()->channels()->Get(i);
696 const Node *node = configuration::GetNode(
697 configuration(), channel->source_node()->string_view());
698
Austin Schuh8bd96322020-02-13 21:18:22 -0800699 State *state =
700 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800701
702 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700703 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800704
705 event_loop_factory_->DisableForwarding(remapped_channel);
706 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700707
708 // If we are replaying a log, we don't want a bunch of redundant messages
709 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700710 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800711 }
Austin Schuh891214d2021-11-11 20:35:02 -0800712
713 // Write pseudo start times out to file now that we are all setup.
714 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700715}
716
717void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
718 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800719 StartAfterRegister(event_loop_factory);
720}
721
722void LogReader::StartAfterRegister(
723 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700724 // We want to start the log file at the last start time of the log files
725 // from all the nodes. Compute how long each node's simulation needs to run
726 // to move time to this point.
727 distributed_clock::time_point start_time = distributed_clock::min_time;
728
729 // TODO(austin): We want an "OnStart" callback for each node rather than
730 // running until the last node.
731
732 for (std::unique_ptr<State> &state : states_) {
733 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
734 << " for node " << MaybeNodeName(state->node()) << "now "
735 << state->monotonic_now();
736 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
737 continue;
738 }
739 // And start computing the start time on the distributed clock now that
740 // that works.
741 start_time = std::max(
742 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
743 }
744
745 // TODO(austin): If a node doesn't have a start time, we might not queue
746 // enough. If this happens, we'll explode with a frozen error eventually.
747
748 CHECK_GE(start_time, distributed_clock::epoch())
749 << ": Hmm, we have a node starting before the start of time. Offset "
750 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800751
Austin Schuhcde938c2020-02-02 17:30:07 -0800752 // While we are starting the system up, we might be relying on matching data
753 // to timestamps on log files where the timestamp log file starts before the
754 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800755 {
756 const bool prior_ignore_missing_data = ignore_missing_data_;
757 ignore_missing_data_ = true;
758 VLOG(1) << "Running until " << start_time << " in Register";
759 event_loop_factory_->RunFor(start_time.time_since_epoch());
760 VLOG(1) << "At start time";
761 // Now that we are running for real, missing data means that the log file is
762 // corrupted or went wrong.
763 ignore_missing_data_ = prior_ignore_missing_data;
764 }
Austin Schuh92547522019-12-28 14:33:43 -0800765
Austin Schuh8bd96322020-02-13 21:18:22 -0800766 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700767 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700768 if (state->realtime_start_time(0) != realtime_clock::min_time) {
769 state->SetRealtimeOffset(state->monotonic_start_time(0),
770 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700771 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700772 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
773 << " for node " << MaybeNodeName(state->event_loop()->node())
774 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700775 }
776
777 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800778 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800779 }
780}
781
Austin Schuh2f8fd752020-09-01 22:38:28 -0700782message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800783 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800784 if (filters_) {
785 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800786 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800787 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800788}
789
James Kuszmaul09632422022-05-25 15:56:19 -0700790// TODO(jkuszmaul): Make in-line modifications to
791// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
792// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800793void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700794 filters_ =
795 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
796 event_loop->configuration(), logged_configuration(),
797 log_files_[0].boots, FLAGS_skip_order_validation,
798 chrono::duration_cast<chrono::nanoseconds>(
799 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
800
801 std::vector<TimestampMapper *> timestamp_mappers;
802 for (const Node *node : configuration::GetNodes(configuration())) {
803 const size_t node_index =
804 configuration::GetNodeIndex(configuration(), node);
805 std::vector<LogParts> filtered_parts = FilterPartsForNode(
806 log_files_, node != nullptr ? node->name()->string_view() : "");
807
808 states_[node_index] = std::make_unique<State>(
809 filtered_parts.size() == 0u
810 ? nullptr
811 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700812 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800813 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node));
James Kuszmaul09632422022-05-25 15:56:19 -0700814 State *state = states_[node_index].get();
815
816 state->SetChannelCount(logged_configuration()->channels()->size());
817 timestamp_mappers.emplace_back(state->timestamp_mapper());
818 }
819
820 filters_->SetTimestampMappers(std::move(timestamp_mappers));
821
822 for (const Node *node : configuration::GetNodes(configuration())) {
823 const size_t node_index =
824 configuration::GetNodeIndex(configuration(), node);
825 State *state = states_[node_index].get();
826 for (const Node *other_node : configuration::GetNodes(configuration())) {
827 const size_t other_node_index =
828 configuration::GetNodeIndex(configuration(), other_node);
829 State *other_state = states_[other_node_index].get();
830 if (other_state != state) {
831 state->AddPeer(other_state);
832 }
833 }
834 }
835 for (const Node *node : configuration::GetNodes(configuration())) {
836 if (node == nullptr || node->name()->string_view() ==
837 event_loop->node()->name()->string_view()) {
838 Register(event_loop, event_loop->node());
839 } else {
840 Register(nullptr, node);
841 }
842 }
Austin Schuh58646e22021-08-23 23:51:46 -0700843}
844
845void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800846 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700847 states_[configuration::GetNodeIndex(configuration(), node)].get();
848
849 // If we didn't find any log files with data in them, we won't ever get a
850 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700851 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700852 return;
853 }
James Kuszmaul09632422022-05-25 15:56:19 -0700854
855 if (event_loop != nullptr) {
856 ++live_nodes_;
857 }
Austin Schuh58646e22021-08-23 23:51:46 -0700858
859 if (event_loop_factory_ != nullptr) {
860 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
861 [this, event_loop, node]() {
862 RegisterDuringStartup(event_loop, node);
863 });
864 } else {
865 RegisterDuringStartup(event_loop, node);
866 }
867}
868
869void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700870 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700871 CHECK(event_loop->configuration() == configuration());
872 }
873
874 State *state =
875 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800876
James Kuszmaul09632422022-05-25 15:56:19 -0700877 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800878 state->ClearTimeFlags();
879 }
880
Austin Schuh858c9f32020-08-31 16:56:12 -0700881 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800882
Tyler Chatow67ddb032020-01-12 14:30:04 -0800883 // We don't run timing reports when trying to print out logged data, because
884 // otherwise we would end up printing out the timing reports themselves...
885 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700886 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700887 event_loop->SkipTimingReport();
888 event_loop->SkipAosLog();
889 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800890
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700891 for (size_t logged_channel_index = 0;
892 logged_channel_index < logged_configuration()->channels()->size();
893 ++logged_channel_index) {
894 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700895 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700896 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800897
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700898 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700899 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700900
901 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700902
Austin Schuh58646e22021-08-23 23:51:46 -0700903 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
904 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700905 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700906 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800907
Austin Schuh58646e22021-08-23 23:51:46 -0700908 // We've got a message which is being forwarded to this node.
909 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700910
911 source_state =
912 states_[configuration::GetNodeIndex(configuration(), source_node)]
913 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800914 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700915
Austin Schuh58646e22021-08-23 23:51:46 -0700916 // We are the source, and it is forwarded.
917 const bool is_forwarded =
918 configuration::ChannelIsSendableOnNode(channel, node) &&
919 configuration::ConnectionCount(channel);
920
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700921 state->SetChannel(
922 logged_channel_index,
923 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700924 event_loop && logged &&
925 configuration::ChannelIsReadableOnNode(channel, node)
926 ? event_loop->MakeRawSender(channel)
927 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700928 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700929
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700930 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700931 const Node *source_node = configuration::GetNode(
932 configuration(), channel->source_node()->string_view());
933
934 for (const Connection *connection : *channel->destination_nodes()) {
935 const bool delivery_time_is_logged =
936 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
937 source_node);
938
939 if (delivery_time_is_logged) {
940 State *destination_state =
941 states_[configuration::GetNodeIndex(
942 configuration(), connection->name()->string_view())]
943 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700944 if (destination_state) {
945 destination_state->SetRemoteTimestampSender(
946 logged_channel_index,
947 event_loop ? state->RemoteTimestampSender(channel, connection)
948 : nullptr);
949 }
Austin Schuh58646e22021-08-23 23:51:46 -0700950 }
951 }
952 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800953 }
954
Austin Schuh58646e22021-08-23 23:51:46 -0700955 if (!event_loop) {
956 state->ClearRemoteTimestampSenders();
957 state->set_timer_handler(nullptr);
958 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800959 return;
960 }
961
Austin Schuh858c9f32020-08-31 16:56:12 -0700962 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700963 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800964 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700965 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700966 if (exit_on_finish_ && live_nodes_ == 0 &&
967 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700968 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800969 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800970 return;
971 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700972
Austin Schuhdda74ec2021-01-03 19:30:37 -0800973 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700974
975 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
976 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800977
Austin Schuhe309d2a2019-11-29 13:25:21 -0800978 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700979 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700980 if (event_loop_factory_ != nullptr) {
981 // Only enforce exact timing in simulation.
982 if (!FLAGS_skip_order_validation) {
983 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
984 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
985 << monotonic_now << " trying to send "
986 << timestamped_message.monotonic_event_time << " failure "
987 << state->DebugString();
988 } else if (BootTimestamp{.boot = state->boot_count(),
989 .time = monotonic_now} !=
990 timestamped_message.monotonic_event_time) {
991 LOG(WARNING) << "Check failed: monotonic_now == "
992 "timestamped_message.monotonic_event_time) ("
993 << monotonic_now << " vs. "
994 << timestamped_message.monotonic_event_time
995 << "): " << FlatbufferToJson(state->event_loop()->node())
996 << " Now " << monotonic_now << " trying to send "
997 << timestamped_message.monotonic_event_time << " failure "
998 << state->DebugString();
999 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001000 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001001
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001002 if (timestamped_message.monotonic_event_time.time >
1003 state->monotonic_start_time(
1004 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -07001005 event_loop_factory_ != nullptr ||
1006 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001007 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001008 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001009 BootTimestamp::min_time() &&
1010 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001011 // Confirm that the message was sent on the sending node before the
1012 // destination node (this node). As a proxy, do this by making sure
1013 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001014 //
1015 // TODO(austin): <= means that the cause message (which we know) could
1016 // happen after the effect even though we know they are at the same
1017 // time. I doubt anyone will notice for a bit, but we should really
1018 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001019 BootTimestamp monotonic_remote_now =
1020 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001021 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001022 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001023 monotonic_remote_now.boot)
1024 << state->event_loop()->node()->name()->string_view() << " to "
1025 << state->remote_node(timestamped_message.channel_index)
1026 ->name()
1027 ->string_view()
1028 << " while trying to send a message on "
1029 << configuration::CleanedChannelToString(
1030 logged_configuration()->channels()->Get(
1031 timestamped_message.channel_index))
1032 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001033 CHECK_LE(timestamped_message.monotonic_remote_time,
1034 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001035 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001036 << state->remote_node(timestamped_message.channel_index)
1037 ->name()
1038 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001039 << " while trying to send a message on "
1040 << configuration::CleanedChannelToString(
1041 logged_configuration()->channels()->Get(
1042 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001043 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001044 } else if (monotonic_remote_now.boot !=
1045 timestamped_message.monotonic_remote_time.boot) {
1046 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1047 << " vs "
1048 << timestamped_message.monotonic_remote_time.boot;
1049 } else if (timestamped_message.monotonic_remote_time >
1050 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001051 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001052 << "Check failed: timestamped_message.monotonic_remote_time < "
1053 "state->monotonic_remote_now(timestamped_message.channel_"
1054 "index) ("
1055 << timestamped_message.monotonic_remote_time << " vs. "
1056 << state->monotonic_remote_now(
1057 timestamped_message.channel_index)
1058 << ") " << state->event_loop()->node()->name()->string_view()
1059 << " to "
1060 << state->remote_node(timestamped_message.channel_index)
1061 ->name()
1062 ->string_view()
1063 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 << " ("
1065 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001066 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001067 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001068 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001069 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001070 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001071 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001072 << ") " << state->DebugString();
1073 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001074 }
1075
Austin Schuh15649d62019-12-28 16:36:38 -08001076 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001077 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001078 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001079
Austin Schuh2f8fd752020-09-01 22:38:28 -07001080 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001081 << timestamped_message.monotonic_event_time << " "
1082 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001083 // TODO(austin): std::move channel_data in and make that efficient in
1084 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001085 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001086 } else if (state->found_last_message() ||
1087 (!ignore_missing_data_ &&
1088 // When starting up, we can have data which was sent before
1089 // the log starts, but the timestamp was after the log
1090 // starts. This is unreasonable to avoid, so ignore the
1091 // missing data.
1092 timestamped_message.monotonic_remote_time.time >=
1093 state->monotonic_remote_start_time(
1094 timestamped_message.monotonic_remote_time.boot,
1095 timestamped_message.channel_index) &&
1096 !FLAGS_skip_missing_forwarding_entries)) {
1097 if (!state->found_last_message()) {
1098 // We've found a timestamp without data that we expect to have data
1099 // for. This likely means that we are at the end of the log file.
1100 // Record it and CHECK that in the rest of the log file, we don't find
1101 // any more data on that channel. Not all channels will end at the
1102 // same point in time since they can be in different files.
1103 VLOG(1) << "Found the last message on channel "
1104 << timestamped_message.channel_index << ", "
1105 << configuration::CleanedChannelToString(
1106 logged_configuration()->channels()->Get(
1107 timestamped_message.channel_index))
1108 << " on node " << MaybeNodeName(state->event_loop()->node())
1109 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001110
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001111 // The user might be working with log files from 1 node but forgot to
1112 // configure the infrastructure to log data for a remote channel on
1113 // that node. That can be very hard to debug, even though the log
1114 // reader is doing the right thing. At least log a warning in that
1115 // case and tell the user what is happening so they can either update
1116 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001117 const std::vector<std::string> logger_nodes =
1118 FindLoggerNodes(log_files_);
1119 if (logger_nodes.size()) {
1120 // We have old logs which don't have the logger nodes logged. In
1121 // that case, we can't be helpful :(
1122 bool data_logged = false;
1123 const Channel *channel = logged_configuration()->channels()->Get(
1124 timestamped_message.channel_index);
1125 for (const std::string &node : logger_nodes) {
1126 data_logged |=
1127 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1128 }
1129 if (!data_logged) {
1130 LOG(WARNING) << "Got a timestamp without any logfiles which "
1131 "could contain data for channel "
1132 << configuration::CleanedChannelToString(channel);
1133 LOG(WARNING) << "Only have logs logged on ["
1134 << absl::StrJoin(logger_nodes, ", ") << "]";
1135 LOG(WARNING)
1136 << "Dropping the rest of the data on "
1137 << state->event_loop()->node()->name()->string_view();
1138 LOG(WARNING)
1139 << "Consider using --skip_missing_forwarding_entries to "
1140 "bypass this, update your config to log it, or add data "
1141 "from one of the nodes it is logged on.";
1142 }
1143 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001144 // Now that we found the end of one channel, artificially stop the
1145 // rest by setting the found_last_message bit. It is confusing when
1146 // part of your data gets replayed but not all. The rest of them will
1147 // get dropped as they are replayed to keep memory usage down.
1148 state->SetFoundLastMessage(true);
1149
1150 // Vector storing if we've seen a nullptr message or not per channel.
1151 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001152 }
1153
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001154 // Make sure that once we have seen the last message on a channel,
1155 // data doesn't start back up again. If the user wants to play
1156 // through events like this, they can set
1157 // --skip_missing_forwarding_entries or ignore_missing_data_.
1158 if (timestamped_message.data == nullptr) {
1159 state->set_last_message(timestamped_message.channel_index);
1160 } else {
1161 if (state->last_message(timestamped_message.channel_index)) {
1162 LOG(FATAL) << "Found missing data in the middle of the log file on "
1163 "channel "
1164 << timestamped_message.channel_index << " "
1165 << configuration::StrippedChannelToString(
1166 logged_configuration()->channels()->Get(
1167 timestamped_message.channel_index))
1168 << " " << timestamped_message << " "
1169 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001170 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001171 }
Austin Schuh92547522019-12-28 14:33:43 -08001172 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001173 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001174 LOG(WARNING)
1175 << "Not sending data from before the start of the log file. "
1176 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1177 .count()
1178 << " start "
1179 << monotonic_start_time(state->node()).time_since_epoch().count()
1180 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001181 }
1182
James Kuszmaula16a7912022-06-17 10:58:12 -07001183 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001184 if (next_time != BootTimestamp::max_time()) {
1185 if (next_time.boot != state->boot_count()) {
1186 VLOG(1) << "Next message for "
1187 << MaybeNodeName(state->event_loop()->node())
1188 << "is on the next boot, " << next_time << " now is "
1189 << state->monotonic_now();
1190 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001191 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001192 return;
1193 }
James Kuszmaul09632422022-05-25 15:56:19 -07001194 if (event_loop_factory_ != nullptr) {
1195 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1196 << "wakeup for " << next_time.time << "("
1197 << state->ToDistributedClock(next_time.time)
1198 << " distributed), now is " << state->monotonic_now();
1199 } else {
1200 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1201 << "wakeup for " << next_time.time << ", now is "
1202 << state->monotonic_now();
1203 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001204 // TODO(james): This can result in negative times getting passed-through
1205 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001206 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001207 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001208 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1209 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001210 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001211 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001212 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001213 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001214 // Doesn't apply to single-EventLoop replay since the watchers in question
1215 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001216 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001217 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1218 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001219 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001220 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001221
Austin Schuh2f8fd752020-09-01 22:38:28 -07001222 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1223 << state->event_loop()->context().monotonic_event_time << " now "
1224 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001225 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001226
James Kuszmaula16a7912022-06-17 10:58:12 -07001227 state->SeedSortedMessages();
1228
1229 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001230 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001231 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1232 if (start_time_ != realtime_clock::min_time) {
1233 state->SetStartTimeFlag(start_time_);
1234 }
1235 if (end_time_ != realtime_clock::max_time) {
1236 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001237 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001238 }
Austin Schuh58646e22021-08-23 23:51:46 -07001239 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001240 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001241 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001242 // Queue up messages and then set clock offsets (we don't want to set
1243 // clock offsets before we've done the work of getting the first messages
1244 // primed).
1245 state->QueueThreadUntil(
1246 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1247 std::chrono::duration<double>(
1248 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001249 state->MaybeSetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001250 state->Setup(next_time.time);
1251 state->SetupStartupTimer();
1252 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001253 }
1254}
1255
Austin Schuhe33c08d2022-02-03 18:15:21 -08001256void LogReader::SetEndTime(std::string end_time) {
1257 if (end_time.empty()) {
1258 SetEndTime(realtime_clock::max_time);
1259 } else {
1260 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1261 aos::realtime_clock::FromString(end_time);
1262 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1263 << "'. Expected a date in the format of "
1264 "2021-01-15_15-30-35.000000000.";
1265 SetEndTime(*parsed_end_time);
1266 }
1267}
1268
1269void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1270 end_time_ = end_time;
1271}
1272
1273void LogReader::SetStartTime(std::string start_time) {
1274 if (start_time.empty()) {
1275 SetStartTime(realtime_clock::min_time);
1276 } else {
1277 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1278 aos::realtime_clock::FromString(start_time);
1279 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1280 << "'. Expected a date in the format of "
1281 "2021-01-15_15-30-35.000000000.";
1282 SetStartTime(*parsed_start_time);
1283 }
1284}
1285
1286void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1287 start_time_ = start_time;
1288}
1289
Austin Schuhe309d2a2019-11-29 13:25:21 -08001290void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001291 // Make sure that things get destroyed in the correct order, rather than
1292 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001293 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001294 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001295 }
Austin Schuh92547522019-12-28 14:33:43 -08001296
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001297 event_loop_factory_unique_ptr_.reset();
1298 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001299}
1300
James Kuszmaul53da7f32022-09-11 11:11:55 -07001301namespace {
1302// Checks if the specified channel name/type exists in the config and, depending
1303// on the value of conflict_handling, calls conflict_handler or just dies.
1304template <typename F>
1305void CheckAndHandleRemapConflict(std::string_view new_name,
1306 std::string_view new_type,
1307 const Configuration *config,
1308 LogReader::RemapConflict conflict_handling,
1309 F conflict_handler) {
1310 const Channel *existing_channel =
1311 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1312 if (existing_channel != nullptr) {
1313 switch (conflict_handling) {
1314 case LogReader::RemapConflict::kDisallow:
1315 LOG(FATAL)
1316 << "Channel "
1317 << configuration::StrippedChannelToString(existing_channel)
1318 << " is already used--you can't remap a logged channel to it.";
1319 break;
1320 case LogReader::RemapConflict::kCascade:
1321 LOG(INFO) << "Automatically remapping "
1322 << configuration::StrippedChannelToString(existing_channel)
1323 << " to avoid conflicts.";
1324 conflict_handler();
1325 break;
1326 }
1327 }
1328}
1329} // namespace
1330
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001331void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001332 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001333 std::string_view new_type,
1334 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001335 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1336 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001337}
1338
Austin Schuh01b4c352020-09-21 23:09:39 -07001339void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1340 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001341 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001342 std::string_view new_type,
1343 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001344 if (node != nullptr) {
1345 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1346 }
1347 if (replay_channels_ != nullptr) {
1348 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1349 std::make_pair(std::string{name}, std::string{type})) !=
1350 replay_channels_->end())
1351 << "Attempted to remap channel " << name << " " << type
1352 << " which is not included in the replay channels passed to LogReader.";
1353 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001354 const Channel *remapped_channel =
1355 configuration::GetChannel(logged_configuration(), name, type, "", node);
1356 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1357 << "\", \"type\": \"" << type << "\"}";
1358 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1359 << "\"}";
1360 VLOG(1) << "Remapped "
1361 << aos::configuration::StrippedChannelToString(remapped_channel);
1362
1363 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1364 // we want it to degrade if the heuristics fail to just work.
1365 //
1366 // The easiest way to do this is going to be incredibly specific and verbose.
1367 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1368 // /original/0/spray. Then, create a map from /original/spray to
1369 // /original/0/spray for just the type we were asked for.
1370 if (name != remapped_channel->name()->string_view()) {
1371 MapT new_map;
1372 new_map.match = std::make_unique<ChannelT>();
1373 new_map.match->name = absl::StrCat(add_prefix, name);
1374 new_map.match->type = type;
1375 if (node != nullptr) {
1376 new_map.match->source_node = node->name()->str();
1377 }
1378 new_map.rename = std::make_unique<ChannelT>();
1379 new_map.rename->name =
1380 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1381 maps_.emplace_back(std::move(new_map));
1382 }
1383
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001384 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001385 const size_t channel_index =
1386 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1387 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1388 << "Already remapped channel "
1389 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001390
1391 RemappedChannel remapped_channel_struct;
1392 remapped_channel_struct.remapped_name =
1393 std::string(add_prefix) +
1394 std::string(remapped_channel->name()->string_view());
1395 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001396 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1397 CheckAndHandleRemapConflict(
1398 remapped_channel_struct.remapped_name, remapped_type,
1399 remapped_configuration_, conflict_handling,
1400 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1401 conflict_handling]() {
1402 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1403 node, add_prefix, "", conflict_handling);
1404 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001405 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001406 MakeRemappedConfig();
1407}
1408
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001409void LogReader::RenameLoggedChannel(const std::string_view name,
1410 const std::string_view type,
1411 const std::string_view new_name,
1412 const std::vector<MapT> &add_maps) {
1413 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1414}
1415
1416void LogReader::RenameLoggedChannel(const std::string_view name,
1417 const std::string_view type,
1418 const Node *const node,
1419 const std::string_view new_name,
1420 const std::vector<MapT> &add_maps) {
1421 if (node != nullptr) {
1422 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1423 }
1424 // First find the channel and rename it.
1425 const Channel *remapped_channel =
1426 configuration::GetChannel(logged_configuration(), name, type, "", node);
1427 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1428 << "\", \"type\": \"" << type << "\"}";
1429 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1430 << "\"}";
1431 VLOG(1) << "Remapped "
1432 << aos::configuration::StrippedChannelToString(remapped_channel);
1433
1434 const size_t channel_index =
1435 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1436 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1437 << "Already remapped channel "
1438 << configuration::CleanedChannelToString(remapped_channel);
1439
1440 RemappedChannel remapped_channel_struct;
1441 remapped_channel_struct.remapped_name = new_name;
1442 remapped_channel_struct.new_type.clear();
1443 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1444
1445 // Then add any provided maps.
1446 for (const MapT &map : add_maps) {
1447 maps_.push_back(map);
1448 }
1449
1450 // Finally rewrite the config.
1451 MakeRemappedConfig();
1452}
1453
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001454void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001455 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001456 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001457 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001458 << ": Can't change the mapping after the events are scheduled.";
1459 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001460 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001461
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001462 // If no remapping occurred and we are using the original config, then there
1463 // is nothing interesting to do here.
1464 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001465 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001466 return;
1467 }
1468 // Config to copy Channel definitions from. Use the specified
1469 // replay_configuration_ if it has been provided.
1470 const Configuration *const base_config = replay_configuration_ == nullptr
1471 ? logged_configuration()
1472 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001473
1474 // Create a config with all the channels, but un-sorted/merged. Collect up
1475 // the schemas while we do this. Call MergeConfiguration to sort everything,
1476 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001477
1478 // This is the builder that we use for the config containing all the new
1479 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001480 flatbuffers::FlatBufferBuilder fbb;
1481 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001482 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001483
1484 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1485 << ": Merging logic needs to be updated when the number of channel "
1486 "fields changes.";
1487
1488 // List of schemas.
1489 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1490 // Make sure our new RemoteMessage schema is in there for old logs without it.
1491 schema_map.insert(std::make_pair(
1492 RemoteMessage::GetFullyQualifiedName(),
1493 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1494 message_bridge::RemoteMessageSchema()))));
1495
1496 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001497 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001498 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001499 base_config, logged_configuration()->channels()->Get(pair.first), "",
1500 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001501 channel_offsets.emplace_back(
1502 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001503
1504 if (c->has_destination_nodes()) {
1505 for (const Connection *connection : *c->destination_nodes()) {
1506 switch (connection->timestamp_logger()) {
1507 case LoggerConfig::LOCAL_LOGGER:
1508 case LoggerConfig::NOT_LOGGED:
1509 // There is no timestamp channel associated with this, so ignore it.
1510 break;
1511
1512 case LoggerConfig::REMOTE_LOGGER:
1513 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1514 // We want to make a split timestamp channel regardless of what type
1515 // of log this used to be. No sense propagating the single
1516 // timestamp channel.
1517
1518 CHECK(connection->has_timestamp_logger_nodes());
1519 for (const flatbuffers::String *timestamp_logger_node :
1520 *connection->timestamp_logger_nodes()) {
1521 const Node *node = configuration::GetNode(
1522 logged_configuration(), timestamp_logger_node->string_view());
1523 message_bridge::ChannelTimestampFinder finder(
1524 logged_configuration(), "log_reader", node);
1525
1526 // We are assuming here that all the maps are setup correctly to
1527 // handle arbitrary timestamps. Apply the maps for this node to
1528 // see what name this ends up with.
1529 std::string name = finder.SplitChannelName(
1530 pair.second.remapped_name, c->type()->str(), connection);
1531 std::string unmapped_name = name;
1532 configuration::HandleMaps(logged_configuration()->maps(), &name,
1533 "aos.message_bridge.RemoteMessage",
1534 node);
1535 CHECK_NE(name, unmapped_name)
1536 << ": Remote timestamp channel was not remapped, this is "
1537 "very fishy";
1538 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1539 fbb.CreateString(name);
1540 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1541 fbb.CreateString("aos.message_bridge.RemoteMessage");
1542 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1543 fbb.CreateString(timestamp_logger_node->string_view());
1544
1545 // Now, build a channel. Don't log it, 2 senders, and match the
1546 // source frequency.
1547 Channel::Builder channel_builder(fbb);
1548 channel_builder.add_name(channel_name_offset);
1549 channel_builder.add_type(channel_type_offset);
1550 channel_builder.add_source_node(source_node_offset);
1551 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1552 channel_builder.add_num_senders(2);
1553 if (c->has_frequency()) {
1554 channel_builder.add_frequency(c->frequency());
1555 }
1556 channel_offsets.emplace_back(channel_builder.Finish());
1557 }
1558 break;
1559 }
1560 }
1561 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001562 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001563
Austin Schuh0de30f32020-12-06 12:44:28 -08001564 // Now reconstruct the original channels, translating types as needed
1565 for (const Channel *c : *base_config->channels()) {
1566 // Search for a mapping channel.
1567 std::string_view new_type = "";
1568 for (auto &pair : remapped_channels_) {
1569 const Channel *const remapped_channel =
1570 logged_configuration()->channels()->Get(pair.first);
1571 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1572 remapped_channel->type()->string_view() == c->type()->string_view()) {
1573 new_type = pair.second.new_type;
1574 break;
1575 }
1576 }
1577
1578 // Copy everything over.
1579 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1580
1581 // Add the schema if it doesn't exist.
1582 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1583 CHECK(c->has_schema());
1584 schema_map.insert(std::make_pair(c->type()->string_view(),
1585 RecursiveCopyFlatBuffer(c->schema())));
1586 }
1587 }
1588
1589 // The MergeConfiguration API takes a vector, not a map. Convert.
1590 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1591 while (!schema_map.empty()) {
1592 schemas.emplace_back(std::move(schema_map.begin()->second));
1593 schema_map.erase(schema_map.begin());
1594 }
1595
1596 // Create the Configuration containing the new channels that we want to add.
1597 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1598 channels_offset =
1599 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1600
1601 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001602 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001603 if (base_config->maps()) {
1604 for (const Map *map : *base_config->maps()) {
1605 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1606 }
1607 }
1608
1609 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001610 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001611 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001612 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001613 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001614 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1615 if (!map.match->type.empty()) {
1616 match_type_offset = fbb.CreateString(map.match->type);
1617 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001618 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1619 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001620 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001621 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001622 CHECK(!map.rename->name.empty());
1623 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1624 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001625 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001626 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001627 if (!match_type_offset.IsNull()) {
1628 match_builder.add_type(match_type_offset);
1629 }
1630 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001631 match_builder.add_source_node(match_source_node_offset);
1632 }
1633 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1634
Austin Schuh0de30f32020-12-06 12:44:28 -08001635 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001636 rename_builder.add_name(rename_name_offset);
1637 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1638
Austin Schuh0de30f32020-12-06 12:44:28 -08001639 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001640 map_builder.add_match(match_offset);
1641 map_builder.add_rename(rename_offset);
1642 map_offsets.emplace_back(map_builder.Finish());
1643 }
1644
Austin Schuh0de30f32020-12-06 12:44:28 -08001645 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1646 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001647
Austin Schuh0de30f32020-12-06 12:44:28 -08001648 // And copy everything else over.
1649 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1650 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1651
1652 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1653 applications_offset =
1654 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1655
1656 // Now insert everything else in unmodified.
1657 ConfigurationBuilder configuration_builder(fbb);
1658 if (!channels_offset.IsNull()) {
1659 configuration_builder.add_channels(channels_offset);
1660 }
1661 if (!maps_offsets.IsNull()) {
1662 configuration_builder.add_maps(maps_offsets);
1663 }
1664 if (!nodes_offset.IsNull()) {
1665 configuration_builder.add_nodes(nodes_offset);
1666 }
1667 if (!applications_offset.IsNull()) {
1668 configuration_builder.add_applications(applications_offset);
1669 }
1670
1671 if (base_config->has_channel_storage_duration()) {
1672 configuration_builder.add_channel_storage_duration(
1673 base_config->channel_storage_duration());
1674 }
1675
1676 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1677 << ": Merging logic needs to be updated when the number of configuration "
1678 "fields changes.";
1679
1680 fbb.Finish(configuration_builder.Finish());
1681
1682 // Clean it up and return it! By using MergeConfiguration here, we'll
1683 // actually get a deduplicated config for free too.
1684 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1685 configuration::MergeConfiguration(
1686 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1687
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001688 remapped_configuration_buffer_ =
1689 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001690 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001691
1692 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001693
1694 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001695}
1696
Naman Guptacf6d4422023-03-01 11:41:00 -08001697std::unique_ptr<const ReplayChannelIndices>
1698LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001699 if (replay_channels_ == nullptr) {
1700 return nullptr;
1701 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001702 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1703 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001704 for (auto const &channel : *replay_channels_) {
1705 const Channel *ch = configuration::GetChannel(
1706 logged_configuration(), channel.first, channel.second, "", node);
1707 if (ch == nullptr) {
1708 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1709 << " not found in configuration for node: "
1710 << node->name()->string_view() << " Skipping ...";
1711 continue;
1712 }
1713 const size_t channel_index =
1714 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001715 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001716 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001717 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1718 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001719 }
1720}
1721
Austin Schuh1c227352021-09-17 12:53:54 -07001722std::vector<const Channel *> LogReader::RemappedChannels() const {
1723 std::vector<const Channel *> result;
1724 result.reserve(remapped_channels_.size());
1725 for (auto &pair : remapped_channels_) {
1726 const Channel *const logged_channel =
1727 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1728
1729 auto channel_iterator = std::lower_bound(
1730 remapped_configuration_->channels()->cbegin(),
1731 remapped_configuration_->channels()->cend(),
1732 std::make_pair(std::string_view(pair.second.remapped_name),
1733 logged_channel->type()->string_view()),
1734 CompareChannels);
1735
1736 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1737 CHECK(EqualsChannels(
1738 *channel_iterator,
1739 std::make_pair(std::string_view(pair.second.remapped_name),
1740 logged_channel->type()->string_view())));
1741 result.push_back(*channel_iterator);
1742 }
1743 return result;
1744}
1745
Austin Schuh6f3babe2020-01-26 20:34:50 -08001746const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001747 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001748 const Channel *channel) {
1749 std::string_view channel_name = channel->name()->string_view();
1750 std::string_view channel_type = channel->type()->string_view();
1751 const int channel_index =
1752 configuration::ChannelIndex(logged_configuration(), channel);
1753 // If the channel is remapped, find the correct channel name to use.
1754 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001755 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001756 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001757 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001758 }
1759
Austin Schuhee711052020-08-24 16:06:09 -07001760 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001761 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001762 configuration(), channel_name, channel_type,
1763 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001764
1765 CHECK(remapped_channel != nullptr)
1766 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1767 << channel_type << "\"} because it is not in the provided configuration.";
1768
1769 return remapped_channel;
1770}
1771
James Kuszmaul09632422022-05-25 15:56:19 -07001772LogReader::State::State(
1773 std::unique_ptr<TimestampMapper> timestamp_mapper,
1774 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001775 std::function<void()> notice_realtime_end, const Node *node,
1776 LogReader::State::ThreadedBuffering threading,
Naman Guptacf6d4422023-03-01 11:41:00 -08001777 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices)
James Kuszmaul09632422022-05-25 15:56:19 -07001778 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001779 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001780 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001781 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001782 threading_(threading),
Naman Guptacf6d4422023-03-01 11:41:00 -08001783 replay_channel_indices_(std::move(replay_channel_indices)) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001784 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1785 // with this node. If there are no log parts for the node, there will be no
1786 // log data, and so we do not need to worry about the replay channel filters.
1787 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001788 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001789 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001790 const TimestampedMessage &message) -> bool {
1791 auto const begin = filter->cbegin();
1792 auto const end = filter->cend();
1793 // TODO: benchmark strategies for channel_index matching
1794 return std::binary_search(begin, end, message.channel_index);
1795 });
1796 }
1797}
Austin Schuh287d43d2020-12-04 20:19:33 -08001798
1799void LogReader::State::AddPeer(State *peer) {
1800 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1801 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1802 }
1803}
Austin Schuh858c9f32020-08-31 16:56:12 -07001804
Austin Schuh58646e22021-08-23 23:51:46 -07001805void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001806 NodeEventLoopFactory *node_event_loop_factory,
1807 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001808 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001809 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001810}
1811
1812void LogReader::State::SetChannelCount(size_t count) {
1813 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001814 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001815 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001816 channel_source_state_.resize(count);
1817 factory_channel_index_.resize(count);
1818 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001819}
1820
Austin Schuh58646e22021-08-23 23:51:46 -07001821void LogReader::State::SetRemoteTimestampSender(
1822 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1823 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1824}
1825
Austin Schuh858c9f32020-08-31 16:56:12 -07001826void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001827 size_t logged_channel_index, size_t factory_channel_index,
1828 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001829 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1830 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001831 channels_[logged_channel_index] = std::move(sender);
1832 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001833 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001834
Austin Schuh58646e22021-08-23 23:51:46 -07001835 if (is_forwarded) {
1836 queue_index_map_[logged_channel_index] =
1837 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001838 }
1839
1840 factory_channel_index_[logged_channel_index] = factory_channel_index;
1841}
1842
James Kuszmaula16a7912022-06-17 10:58:12 -07001843void LogReader::State::TrackMessageSendTiming(
1844 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1845 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1846 return;
1847 }
1848
1849 timing::MessageTimingT sample;
1850 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1851 sender.channel());
1852 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1853 sample.actual_send_time =
1854 sender.monotonic_sent_time().time_since_epoch().count();
1855 sample.send_time_error = aos::time::DurationInSeconds(
1856 expected_send_time - sender.monotonic_sent_time());
1857 send_timings_.push_back(sample);
1858
1859 // Somewhat arbitrarily send out timing information in batches of 100. No need
1860 // to create excessive overhead in regenerated logfiles.
1861 // TODO(james): The overhead may be fine.
1862 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1863 CHECK(timing_statistics_sender_.valid());
1864 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1865 SendMessageTimings();
1866 }
1867}
1868
1869void LogReader::State::SendMessageTimings() {
1870 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1871 return;
1872 }
1873 auto builder = timing_statistics_sender_.MakeBuilder();
1874 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1875 for (const auto &timing : send_timings_) {
1876 timing_offsets.push_back(
1877 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1878 }
1879 send_timings_.clear();
1880 flatbuffers::Offset<
1881 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1882 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1883 timing::ReplayTiming::Builder timing_builder =
1884 builder.MakeBuilder<timing::ReplayTiming>();
1885 timing_builder.add_messages(timings_offset);
1886 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1887}
1888
Austin Schuh287d43d2020-12-04 20:19:33 -08001889bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1890 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001891 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001892 uint32_t remote_queue_index = 0xffffffff;
1893
Austin Schuh287d43d2020-12-04 20:19:33 -08001894 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001895 State *source_state =
1896 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001897 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001898 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001899 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001900
Austin Schuh9942bae2021-01-07 22:06:44 -08001901 struct SentTimestamp {
1902 monotonic_clock::time_point monotonic_event_time;
1903 uint32_t queue_index;
1904 } search;
1905
Austin Schuh58646e22021-08-23 23:51:46 -07001906 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1907 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001908 search.monotonic_event_time =
1909 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001910 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001911
1912 // Find the sent time if available.
1913 auto element = std::lower_bound(
1914 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001915 [](ContiguousSentTimestamp a, SentTimestamp b) {
1916 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001917 return true;
1918 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001919 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001920 return false;
1921 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001922
1923 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001924 return true;
1925 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001926 if (a.starting_queue_index >= b.queue_index) {
1927 return false;
1928 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929
Austin Schuh9942bae2021-01-07 22:06:44 -08001930 // If it isn't clearly below or above, it is below. Since we return
1931 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001932 return false;
1933 });
1934
1935 // TODO(austin): Be a bit more principled here, but we will want to do that
1936 // after the logger rewrite. We hit this when one node finishes, but the
1937 // other node isn't done yet. So there is no send time, but there is a
1938 // receive time.
1939 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001940 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1941 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001942
1943 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001944 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001945 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001946 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001947 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001948 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001949 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001950 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001951
Austin Schuh58646e22021-08-23 23:51:46 -07001952 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001953 element->actual_queue_index -
1954 element->starting_queue_index;
1955 } else {
1956 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001957 }
Austin Schuh58646e22021-08-23 23:51:46 -07001958 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1959 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001960 }
1961
James Kuszmaul09632422022-05-25 15:56:19 -07001962 if (event_loop_factory_ != nullptr &&
1963 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1964 multinode_filters_ != nullptr) {
1965 // Sanity check that we are using consistent boot uuids.
1966 State *source_state =
1967 channel_source_state_[timestamped_message.channel_index];
1968 CHECK_EQ(multinode_filters_->boot_uuid(
1969 configuration::GetNodeIndex(event_loop_->configuration(),
1970 source_state->node()),
1971 timestamped_message.monotonic_remote_time.boot),
1972 CHECK_NOTNULL(
1973 CHECK_NOTNULL(
1974 channel_source_state_[timestamped_message.channel_index])
1975 ->event_loop_)
1976 ->boot_uuid());
1977 }
1978
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001979 // Send! Use the replayed queue index here instead of the logged queue index
1980 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001981 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001982 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001983 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001984 timestamped_message.realtime_remote_time, remote_queue_index,
1985 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001986 ? CHECK_NOTNULL(multinode_filters_)
1987 ->boot_uuid(configuration::GetNodeIndex(
1988 event_loop_->configuration(),
1989 channel_source_state_[timestamped_message
1990 .channel_index]
1991 ->node()),
1992 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001993 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001994 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001995 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1996 timestamped_message.monotonic_event_time.time) {
1997 // Only track errors for non-fetched messages.
1998 TrackMessageSendTiming(
1999 *sender,
2000 timestamped_message.monotonic_event_time.time + clock_offset());
2001 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002002
Austin Schuh287d43d2020-12-04 20:19:33 -08002003 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07002004 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08002005 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
2006 // Nothing here, start a range with 0 length.
2007 ContiguousSentTimestamp timestamp;
2008 timestamp.starting_monotonic_event_time =
2009 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002010 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002011 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002012 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002013 timestamp.actual_queue_index = sender->sent_queue_index();
2014 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2015 timestamp);
2016 } else {
2017 // We've got something. See if the next timestamp is still contiguous. If
2018 // so, grow it.
2019 ContiguousSentTimestamp *back =
2020 &queue_index_map_[timestamped_message.channel_index]->back();
2021 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002022 (timestamped_message.queue_index.index -
2023 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002024 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002025 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002026 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002027 } else {
2028 // Otherwise, make a new one.
2029 ContiguousSentTimestamp timestamp;
2030 timestamp.starting_monotonic_event_time =
2031 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002032 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002033 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002034 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002035 timestamp.actual_queue_index = sender->sent_queue_index();
2036 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2037 timestamp);
2038 }
2039 }
2040
2041 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2042 // queue index diverge a couple of elements, which would be a very small
2043 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002044 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2045 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002046 // TODO(james): Currently, If running replay against a single event loop,
2047 // remote timestamps will not get replayed because this code-path only
2048 // gets triggered on the event loop that receives the forwarded message
2049 // that the timestamps correspond to. This code, as written, also doesn't
2050 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002051 State *source_state =
2052 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2053
Austin Schuh969cd602021-01-03 00:09:45 -08002054 flatbuffers::FlatBufferBuilder fbb;
2055 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002056 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2057 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002058
Austin Schuh969cd602021-01-03 00:09:45 -08002059 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002060
2061 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002062 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002063
2064 // Swap the remote and sent metrics. They are from the sender's
2065 // perspective, not the receiver's perspective.
2066 message_header_builder.add_monotonic_sent_time(
2067 sender->monotonic_sent_time().time_since_epoch().count());
2068 message_header_builder.add_realtime_sent_time(
2069 sender->realtime_sent_time().time_since_epoch().count());
2070 message_header_builder.add_queue_index(sender->sent_queue_index());
2071
Austin Schuh58646e22021-08-23 23:51:46 -07002072 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2073 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002074 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002075 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2076 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002077 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002078 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002079
2080 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002081 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002082
Austin Schuh969cd602021-01-03 00:09:45 -08002083 fbb.Finish(message_header_builder.Finish());
2084
2085 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2086 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002087 timestamped_message.monotonic_timestamp_time,
2088 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002089 }
2090
2091 return true;
2092}
2093
Austin Schuh969cd602021-01-03 00:09:45 -08002094LogReader::RemoteMessageSender::RemoteMessageSender(
2095 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2096 : event_loop_(event_loop),
2097 sender_(std::move(sender)),
2098 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2099
2100void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2101 if (remote_timestamps_.empty()) {
2102 CHECK_NOTNULL(timer_);
2103 timer_->Disable();
2104 scheduled_time_ = monotonic_clock::min_time;
2105 return;
2106 }
2107
2108 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2109 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002110 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002111 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002112 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2113 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002114 }
2115}
2116
2117void LogReader::RemoteMessageSender::Send(
2118 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002119 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002120 // There are 2 variants of logs.
2121 // 1) Logs without monotonic_timestamp_time
2122 // 2) Logs with monotonic_timestamp_time
2123 //
2124 // As of Jan 2021, we shouldn't have any more logs without
2125 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2126 // the effort of saving.
2127 //
2128 // This gives us 3 cases, 2 of which are undistinguishable.
2129 // 1) Old log without monotonic_timestamp_time.
2130 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2131 // remotely so we actually have monotonic_timestamp_time.
2132 // 3) New log, but the timestamp was logged on the node receiving the message
2133 // so there is no monotonic_timestamp_time.
2134 //
2135 // Our goal when replaying is to accurately reproduce the state of the world
2136 // present when logging. If a timestamp wasn't sent back across the network,
2137 // we shouldn't replay one back across the network.
2138 //
2139 // Given that we don't really care about 1, we can use the presence of the
2140 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2141 // monotonic_timestamp_time, this means the message was logged locally and
2142 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002143 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002144 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002145 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002146
Austin Schuh58646e22021-08-23 23:51:46 -07002147 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2148
Austin Schuhc41d6a82021-07-16 14:49:23 -07002149 remote_timestamps_.emplace(
2150 std::upper_bound(
2151 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002152 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002153 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2154 const Timestamp &timestamp) {
2155 return monotonic_timestamp_time <
2156 timestamp.monotonic_timestamp_time;
2157 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002158 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002159 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002160}
2161
2162void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002163 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2164 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002165 CHECK(!remote_timestamps_.empty());
2166
2167 // Send out all timestamps at the currently scheduled time.
2168 while (remote_timestamps_.front().monotonic_timestamp_time ==
2169 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002170 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2171 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002172 remote_timestamps_.pop_front();
2173 if (remote_timestamps_.empty()) {
2174 break;
2175 }
2176 }
2177 scheduled_time_ = monotonic_clock::min_time;
2178
2179 ScheduleTimestamp();
2180}
2181
2182LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002183 const Channel *channel, const Connection *connection) {
2184 message_bridge::ChannelTimestampFinder finder(event_loop_);
2185 // Look at any pre-created channel/connection pairs.
2186 {
2187 auto it =
2188 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2189 if (it != channel_timestamp_loggers_.end()) {
2190 return it->second.get();
2191 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002192 }
2193
Austin Schuh61e973f2021-02-21 21:43:56 -08002194 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2195 // to.
2196 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2197
2198 {
2199 // See if that has been created before. If so, cache it in
2200 // channel_timestamp_loggers_ and return.
2201 auto it = timestamp_loggers_.find(timestamp_channel);
2202 if (it != timestamp_loggers_.end()) {
2203 CHECK(channel_timestamp_loggers_
2204 .try_emplace(std::make_pair(channel, connection), it->second)
2205 .second);
2206 return it->second.get();
2207 }
2208 }
2209
2210 // Otherwise, make a sender, save it, and cache it.
2211 auto result = channel_timestamp_loggers_.try_emplace(
2212 std::make_pair(channel, connection),
2213 std::make_shared<RemoteMessageSender>(
2214 event_loop()->MakeSender<RemoteMessage>(
2215 timestamp_channel->name()->string_view()),
2216 event_loop()));
2217
2218 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2219 .second);
2220 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002221}
2222
Austin Schuhdda74ec2021-01-03 19:30:37 -08002223TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002224 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002225 if (message_queuer_.has_value()) {
2226 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2227 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2228 message_queuer_->SetState(
2229 message.value().monotonic_event_time +
2230 std::chrono::duration_cast<std::chrono::nanoseconds>(
2231 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2232 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002233 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002234 CHECK(timestamp_mapper_ != nullptr);
2235 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2236 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002237
James Kuszmaula16a7912022-06-17 10:58:12 -07002238 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002239
James Kuszmaula16a7912022-06-17 10:58:12 -07002240 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2241 << result.monotonic_event_time;
2242 timestamp_mapper_->PopFront();
2243 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002244
James Kuszmaula16a7912022-06-17 10:58:12 -07002245 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002246
James Kuszmaula16a7912022-06-17 10:58:12 -07002247 VLOG(1) << "Popped " << result
2248 << configuration::CleanedChannelToString(
2249 event_loop_->configuration()->channels()->Get(
2250 factory_channel_index_[result.channel_index]));
2251 return result;
2252 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002253}
2254
James Kuszmaula16a7912022-06-17 10:58:12 -07002255BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2256 if (!message_queuer_.has_value()) {
2257 return SingleThreadedOldestMessageTime();
2258 }
2259 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2260 if (!message.has_value()) {
2261 return BootTimestamp::max_time();
2262 }
2263 if (message.value().monotonic_event_time.boot == boot_count()) {
2264 ObserveNextMessage(message.value().monotonic_event_time.time,
2265 message.value().realtime_event_time);
2266 }
2267 return message.value().monotonic_event_time;
2268}
2269
2270BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2271 CHECK(!message_queuer_.has_value())
2272 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2273 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002274 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002275 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002276 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002277 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2278 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002279 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002280 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002281 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002282 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002283 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2284 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2285 result_ptr->realtime_event_time);
2286 }
Austin Schuh58646e22021-08-23 23:51:46 -07002287 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002288}
2289
2290void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002291 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002292
Austin Schuhe639ea12021-01-25 13:00:22 -08002293 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2294 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002295}
2296
2297void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002298 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002299 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002300 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002301 for (size_t i = 0; i < channels_.size(); ++i) {
2302 channels_[i].reset();
2303 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002304 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002305 channel_timestamp_loggers_.clear();
2306 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002307 event_loop_unique_ptr_.reset();
2308 event_loop_ = nullptr;
2309 timer_handler_ = nullptr;
2310 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002311 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002312}
2313
Austin Schuhe33c08d2022-02-03 18:15:21 -08002314void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2315 if (start_time != realtime_clock::min_time) {
2316 start_event_notifier_ = std::make_unique<EventNotifier>(
2317 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2318 }
2319}
2320
2321void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2322 if (end_time != realtime_clock::max_time) {
2323 end_event_notifier_ = std::make_unique<EventNotifier>(
2324 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2325 }
2326}
2327
2328void LogReader::State::ObserveNextMessage(
2329 monotonic_clock::time_point monotonic_event,
2330 realtime_clock::time_point realtime_event) {
2331 if (start_event_notifier_) {
2332 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2333 }
2334 if (end_event_notifier_) {
2335 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2336 }
2337}
2338
2339void LogReader::State::ClearTimeFlags() {
2340 start_event_notifier_.reset();
2341 end_event_notifier_.reset();
2342}
2343
2344void LogReader::State::NotifyLogfileStart() {
2345 if (start_event_notifier_) {
2346 if (start_event_notifier_->realtime_event_time() >
2347 realtime_start_time(boot_count())) {
2348 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2349 << " > " << realtime_start_time(boot_count());
2350 return;
2351 }
2352 }
2353 if (found_last_message_) {
2354 VLOG(1) << "Last message already found, bailing";
2355 return;
2356 }
2357 RunOnStart();
2358}
2359
2360void LogReader::State::NotifyFlagStart() {
2361 if (start_event_notifier_->realtime_event_time() >=
2362 realtime_start_time(boot_count())) {
2363 RunOnStart();
2364 }
2365}
2366
2367void LogReader::State::NotifyLogfileEnd() {
2368 if (found_last_message_) {
2369 return;
2370 }
2371
2372 if (!stopped_ && started_) {
2373 RunOnEnd();
2374 }
2375}
2376
2377void LogReader::State::NotifyFlagEnd() {
2378 if (!stopped_ && started_) {
2379 RunOnEnd();
2380 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002381 CHECK(notice_realtime_end_);
2382 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002383 }
2384}
2385
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002386void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002387 if (node_event_loop_factory_ == nullptr) {
2388 // If not running with simulated event loop, set the monotonic clock
2389 // offset.
2390 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2391
2392 if (start_event_notifier_) {
2393 start_event_notifier_->SetClockOffset(clock_offset_);
2394 }
2395 if (end_event_notifier_) {
2396 end_event_notifier_->SetClockOffset(clock_offset_);
2397 }
2398 }
2399}
2400
James Kuszmaulb67409b2022-06-20 16:25:03 -07002401void LogReader::SetRealtimeReplayRate(double replay_rate) {
2402 CHECK(event_loop_factory_ != nullptr)
2403 << ": Can't set replay rate without an event loop factory (have you "
2404 "called Register()?).";
2405 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2406}
2407
James Kuszmaulb11a1502022-07-01 16:02:25 -07002408void LogReader::NoticeRealtimeEnd() {
2409 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2410 --live_nodes_with_realtime_time_end_;
2411 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2412 event_loop_factory_ != nullptr) {
2413 event_loop_factory_->Exit();
2414 }
2415}
2416
Austin Schuhe309d2a2019-11-29 13:25:21 -08002417} // namespace logger
2418} // namespace aos