blob: cbe37d51ee162c3141447bdd9f0bbdd30ca7a1de [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_) {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700733 CHECK(state);
Austin Schuh58646e22021-08-23 23:51:46 -0700734 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
735 << " for node " << MaybeNodeName(state->node()) << "now "
736 << state->monotonic_now();
737 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
738 continue;
739 }
740 // And start computing the start time on the distributed clock now that
741 // that works.
742 start_time = std::max(
743 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
744 }
745
746 // TODO(austin): If a node doesn't have a start time, we might not queue
747 // enough. If this happens, we'll explode with a frozen error eventually.
748
749 CHECK_GE(start_time, distributed_clock::epoch())
750 << ": Hmm, we have a node starting before the start of time. Offset "
751 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800752
Austin Schuhdda74ec2021-01-03 19:30:37 -0800753 {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800754 VLOG(1) << "Running until " << start_time << " in Register";
755 event_loop_factory_->RunFor(start_time.time_since_epoch());
756 VLOG(1) << "At start time";
Austin Schuhdda74ec2021-01-03 19:30:37 -0800757 }
Austin Schuh92547522019-12-28 14:33:43 -0800758
Austin Schuh8bd96322020-02-13 21:18:22 -0800759 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700760 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700761 if (state->realtime_start_time(0) != realtime_clock::min_time) {
762 state->SetRealtimeOffset(state->monotonic_start_time(0),
763 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700764 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700765 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
766 << " for node " << MaybeNodeName(state->event_loop()->node())
767 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700768 }
769
770 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800771 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800772 }
773}
774
Austin Schuh2f8fd752020-09-01 22:38:28 -0700775message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800776 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800777 if (filters_) {
778 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800779 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800780 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800781}
782
James Kuszmaul09632422022-05-25 15:56:19 -0700783// TODO(jkuszmaul): Make in-line modifications to
784// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
785// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800786void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700787 filters_ =
788 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
789 event_loop->configuration(), logged_configuration(),
790 log_files_[0].boots, FLAGS_skip_order_validation,
791 chrono::duration_cast<chrono::nanoseconds>(
792 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
793
794 std::vector<TimestampMapper *> timestamp_mappers;
795 for (const Node *node : configuration::GetNodes(configuration())) {
796 const size_t node_index =
797 configuration::GetNodeIndex(configuration(), node);
798 std::vector<LogParts> filtered_parts = FilterPartsForNode(
799 log_files_, node != nullptr ? node->name()->string_view() : "");
800
801 states_[node_index] = std::make_unique<State>(
802 filtered_parts.size() == 0u
803 ? nullptr
804 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700805 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800806 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node));
James Kuszmaul09632422022-05-25 15:56:19 -0700807 State *state = states_[node_index].get();
808
809 state->SetChannelCount(logged_configuration()->channels()->size());
810 timestamp_mappers.emplace_back(state->timestamp_mapper());
811 }
812
813 filters_->SetTimestampMappers(std::move(timestamp_mappers));
814
815 for (const Node *node : configuration::GetNodes(configuration())) {
816 const size_t node_index =
817 configuration::GetNodeIndex(configuration(), node);
818 State *state = states_[node_index].get();
819 for (const Node *other_node : configuration::GetNodes(configuration())) {
820 const size_t other_node_index =
821 configuration::GetNodeIndex(configuration(), other_node);
822 State *other_state = states_[other_node_index].get();
823 if (other_state != state) {
824 state->AddPeer(other_state);
825 }
826 }
827 }
828 for (const Node *node : configuration::GetNodes(configuration())) {
829 if (node == nullptr || node->name()->string_view() ==
830 event_loop->node()->name()->string_view()) {
831 Register(event_loop, event_loop->node());
832 } else {
833 Register(nullptr, node);
834 }
835 }
Austin Schuh58646e22021-08-23 23:51:46 -0700836}
837
838void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800839 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700840 states_[configuration::GetNodeIndex(configuration(), node)].get();
841
842 // If we didn't find any log files with data in them, we won't ever get a
843 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700844 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700845 return;
846 }
James Kuszmaul09632422022-05-25 15:56:19 -0700847
848 if (event_loop != nullptr) {
849 ++live_nodes_;
850 }
Austin Schuh58646e22021-08-23 23:51:46 -0700851
852 if (event_loop_factory_ != nullptr) {
853 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
854 [this, event_loop, node]() {
855 RegisterDuringStartup(event_loop, node);
856 });
857 } else {
858 RegisterDuringStartup(event_loop, node);
859 }
860}
861
862void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700863 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700864 CHECK(event_loop->configuration() == configuration());
865 }
866
867 State *state =
868 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800869
James Kuszmaul09632422022-05-25 15:56:19 -0700870 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800871 state->ClearTimeFlags();
872 }
873
Austin Schuh858c9f32020-08-31 16:56:12 -0700874 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800875
Tyler Chatow67ddb032020-01-12 14:30:04 -0800876 // We don't run timing reports when trying to print out logged data, because
877 // otherwise we would end up printing out the timing reports themselves...
878 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700879 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700880 event_loop->SkipTimingReport();
881 event_loop->SkipAosLog();
882 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800883
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700884 for (size_t logged_channel_index = 0;
885 logged_channel_index < logged_configuration()->channels()->size();
886 ++logged_channel_index) {
887 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700888 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700889 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800890
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700891 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700892 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700893
894 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700895
Austin Schuh58646e22021-08-23 23:51:46 -0700896 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
897 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700898 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700899 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800900
Austin Schuh58646e22021-08-23 23:51:46 -0700901 // We've got a message which is being forwarded to this node.
902 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700903
904 source_state =
905 states_[configuration::GetNodeIndex(configuration(), source_node)]
906 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800907 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700908
Austin Schuh58646e22021-08-23 23:51:46 -0700909 // We are the source, and it is forwarded.
910 const bool is_forwarded =
911 configuration::ChannelIsSendableOnNode(channel, node) &&
912 configuration::ConnectionCount(channel);
913
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700914 state->SetChannel(
915 logged_channel_index,
916 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700917 event_loop && logged &&
918 configuration::ChannelIsReadableOnNode(channel, node)
919 ? event_loop->MakeRawSender(channel)
920 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700921 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700922
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700923 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700924 const Node *source_node = configuration::GetNode(
925 configuration(), channel->source_node()->string_view());
926
927 for (const Connection *connection : *channel->destination_nodes()) {
928 const bool delivery_time_is_logged =
929 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
930 source_node);
931
932 if (delivery_time_is_logged) {
933 State *destination_state =
934 states_[configuration::GetNodeIndex(
935 configuration(), connection->name()->string_view())]
936 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700937 if (destination_state) {
938 destination_state->SetRemoteTimestampSender(
939 logged_channel_index,
940 event_loop ? state->RemoteTimestampSender(channel, connection)
941 : nullptr);
942 }
Austin Schuh58646e22021-08-23 23:51:46 -0700943 }
944 }
945 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800946 }
947
Austin Schuh58646e22021-08-23 23:51:46 -0700948 if (!event_loop) {
949 state->ClearRemoteTimestampSenders();
950 state->set_timer_handler(nullptr);
951 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800952 return;
953 }
954
Austin Schuh858c9f32020-08-31 16:56:12 -0700955 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700956 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800957 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700958 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700959 if (exit_on_finish_ && live_nodes_ == 0 &&
960 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700961 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800962 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800963 return;
964 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700965
Austin Schuhdda74ec2021-01-03 19:30:37 -0800966 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700967
968 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
969 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800970
Austin Schuhe309d2a2019-11-29 13:25:21 -0800971 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700972 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700973 if (event_loop_factory_ != nullptr) {
974 // Only enforce exact timing in simulation.
975 if (!FLAGS_skip_order_validation) {
976 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
977 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
978 << monotonic_now << " trying to send "
979 << timestamped_message.monotonic_event_time << " failure "
980 << state->DebugString();
981 } else if (BootTimestamp{.boot = state->boot_count(),
982 .time = monotonic_now} !=
983 timestamped_message.monotonic_event_time) {
984 LOG(WARNING) << "Check failed: monotonic_now == "
985 "timestamped_message.monotonic_event_time) ("
986 << monotonic_now << " vs. "
987 << timestamped_message.monotonic_event_time
988 << "): " << FlatbufferToJson(state->event_loop()->node())
989 << " Now " << monotonic_now << " trying to send "
990 << timestamped_message.monotonic_event_time << " failure "
991 << state->DebugString();
992 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700993 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800994
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700995 if (timestamped_message.monotonic_event_time.time >
996 state->monotonic_start_time(
997 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700998 event_loop_factory_ != nullptr ||
999 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001000 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001001 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001002 BootTimestamp::min_time() &&
1003 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001004 // Confirm that the message was sent on the sending node before the
1005 // destination node (this node). As a proxy, do this by making sure
1006 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001007 //
1008 // TODO(austin): <= means that the cause message (which we know) could
1009 // happen after the effect even though we know they are at the same
1010 // time. I doubt anyone will notice for a bit, but we should really
1011 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001012 BootTimestamp monotonic_remote_now =
1013 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001014 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001015 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001016 monotonic_remote_now.boot)
1017 << state->event_loop()->node()->name()->string_view() << " to "
1018 << state->remote_node(timestamped_message.channel_index)
1019 ->name()
1020 ->string_view()
1021 << " while trying to send a message on "
1022 << configuration::CleanedChannelToString(
1023 logged_configuration()->channels()->Get(
1024 timestamped_message.channel_index))
1025 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001026 CHECK_LE(timestamped_message.monotonic_remote_time,
1027 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001028 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001029 << state->remote_node(timestamped_message.channel_index)
1030 ->name()
1031 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001032 << " while trying to send a message on "
1033 << configuration::CleanedChannelToString(
1034 logged_configuration()->channels()->Get(
1035 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001036 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001037 } else if (monotonic_remote_now.boot !=
1038 timestamped_message.monotonic_remote_time.boot) {
1039 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1040 << " vs "
1041 << timestamped_message.monotonic_remote_time.boot;
1042 } else if (timestamped_message.monotonic_remote_time >
1043 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001044 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001045 << "Check failed: timestamped_message.monotonic_remote_time < "
1046 "state->monotonic_remote_now(timestamped_message.channel_"
1047 "index) ("
1048 << timestamped_message.monotonic_remote_time << " vs. "
1049 << state->monotonic_remote_now(
1050 timestamped_message.channel_index)
1051 << ") " << state->event_loop()->node()->name()->string_view()
1052 << " to "
1053 << state->remote_node(timestamped_message.channel_index)
1054 ->name()
1055 ->string_view()
1056 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001057 << " ("
1058 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001059 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001060 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001061 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001062 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001063 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001064 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001065 << ") " << state->DebugString();
1066 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001067 }
1068
Austin Schuh15649d62019-12-28 16:36:38 -08001069 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001070 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001071 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001072
Austin Schuh2f8fd752020-09-01 22:38:28 -07001073 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001074 << timestamped_message.monotonic_event_time << " "
1075 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001076 // TODO(austin): std::move channel_data in and make that efficient in
1077 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001078 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001079 } else if (state->found_last_message() ||
1080 (!ignore_missing_data_ &&
1081 // When starting up, we can have data which was sent before
1082 // the log starts, but the timestamp was after the log
1083 // starts. This is unreasonable to avoid, so ignore the
1084 // missing data.
1085 timestamped_message.monotonic_remote_time.time >=
1086 state->monotonic_remote_start_time(
1087 timestamped_message.monotonic_remote_time.boot,
1088 timestamped_message.channel_index) &&
1089 !FLAGS_skip_missing_forwarding_entries)) {
1090 if (!state->found_last_message()) {
1091 // We've found a timestamp without data that we expect to have data
1092 // for. This likely means that we are at the end of the log file.
1093 // Record it and CHECK that in the rest of the log file, we don't find
1094 // any more data on that channel. Not all channels will end at the
1095 // same point in time since they can be in different files.
1096 VLOG(1) << "Found the last message on channel "
1097 << timestamped_message.channel_index << ", "
1098 << configuration::CleanedChannelToString(
1099 logged_configuration()->channels()->Get(
1100 timestamped_message.channel_index))
1101 << " on node " << MaybeNodeName(state->event_loop()->node())
1102 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001103
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001104 // The user might be working with log files from 1 node but forgot to
1105 // configure the infrastructure to log data for a remote channel on
1106 // that node. That can be very hard to debug, even though the log
1107 // reader is doing the right thing. At least log a warning in that
1108 // case and tell the user what is happening so they can either update
1109 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001110 const std::vector<std::string> logger_nodes =
1111 FindLoggerNodes(log_files_);
1112 if (logger_nodes.size()) {
1113 // We have old logs which don't have the logger nodes logged. In
1114 // that case, we can't be helpful :(
1115 bool data_logged = false;
1116 const Channel *channel = logged_configuration()->channels()->Get(
1117 timestamped_message.channel_index);
1118 for (const std::string &node : logger_nodes) {
1119 data_logged |=
1120 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1121 }
1122 if (!data_logged) {
1123 LOG(WARNING) << "Got a timestamp without any logfiles which "
1124 "could contain data for channel "
1125 << configuration::CleanedChannelToString(channel);
1126 LOG(WARNING) << "Only have logs logged on ["
1127 << absl::StrJoin(logger_nodes, ", ") << "]";
1128 LOG(WARNING)
1129 << "Dropping the rest of the data on "
1130 << state->event_loop()->node()->name()->string_view();
1131 LOG(WARNING)
1132 << "Consider using --skip_missing_forwarding_entries to "
1133 "bypass this, update your config to log it, or add data "
1134 "from one of the nodes it is logged on.";
1135 }
1136 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001137 // Now that we found the end of one channel, artificially stop the
1138 // rest by setting the found_last_message bit. It is confusing when
1139 // part of your data gets replayed but not all. The rest of them will
1140 // get dropped as they are replayed to keep memory usage down.
1141 state->SetFoundLastMessage(true);
1142
1143 // Vector storing if we've seen a nullptr message or not per channel.
1144 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001145 }
1146
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001147 // Make sure that once we have seen the last message on a channel,
1148 // data doesn't start back up again. If the user wants to play
1149 // through events like this, they can set
1150 // --skip_missing_forwarding_entries or ignore_missing_data_.
1151 if (timestamped_message.data == nullptr) {
1152 state->set_last_message(timestamped_message.channel_index);
1153 } else {
1154 if (state->last_message(timestamped_message.channel_index)) {
1155 LOG(FATAL) << "Found missing data in the middle of the log file on "
1156 "channel "
1157 << timestamped_message.channel_index << " "
1158 << configuration::StrippedChannelToString(
1159 logged_configuration()->channels()->Get(
1160 timestamped_message.channel_index))
1161 << " " << timestamped_message << " "
1162 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001163 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001164 }
Austin Schuh92547522019-12-28 14:33:43 -08001165 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001166 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001167 LOG(WARNING)
1168 << "Not sending data from before the start of the log file. "
1169 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1170 .count()
1171 << " start "
1172 << monotonic_start_time(state->node()).time_since_epoch().count()
1173 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001174 }
1175
James Kuszmaula16a7912022-06-17 10:58:12 -07001176 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001177 if (next_time != BootTimestamp::max_time()) {
1178 if (next_time.boot != state->boot_count()) {
1179 VLOG(1) << "Next message for "
1180 << MaybeNodeName(state->event_loop()->node())
1181 << "is on the next boot, " << next_time << " now is "
1182 << state->monotonic_now();
1183 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001184 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001185 return;
1186 }
James Kuszmaul09632422022-05-25 15:56:19 -07001187 if (event_loop_factory_ != nullptr) {
1188 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1189 << "wakeup for " << next_time.time << "("
1190 << state->ToDistributedClock(next_time.time)
1191 << " distributed), now is " << state->monotonic_now();
1192 } else {
1193 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1194 << "wakeup for " << next_time.time << ", now is "
1195 << state->monotonic_now();
1196 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001197 // TODO(james): This can result in negative times getting passed-through
1198 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001199 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001200 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001201 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1202 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001203 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001204 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001205 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001206 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001207 // Doesn't apply to single-EventLoop replay since the watchers in question
1208 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001209 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001210 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1211 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001212 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001213 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001214
Austin Schuh2f8fd752020-09-01 22:38:28 -07001215 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1216 << state->event_loop()->context().monotonic_event_time << " now "
1217 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001218 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001219
James Kuszmaula16a7912022-06-17 10:58:12 -07001220 state->SeedSortedMessages();
1221
1222 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001223 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001224 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1225 if (start_time_ != realtime_clock::min_time) {
1226 state->SetStartTimeFlag(start_time_);
1227 }
1228 if (end_time_ != realtime_clock::max_time) {
1229 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001230 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001231 }
Austin Schuh58646e22021-08-23 23:51:46 -07001232 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001233 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001234 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001235 // Queue up messages and then set clock offsets (we don't want to set
1236 // clock offsets before we've done the work of getting the first messages
1237 // primed).
1238 state->QueueThreadUntil(
1239 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1240 std::chrono::duration<double>(
1241 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001242 state->MaybeSetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001243 state->Setup(next_time.time);
1244 state->SetupStartupTimer();
1245 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001246 }
1247}
1248
Austin Schuhe33c08d2022-02-03 18:15:21 -08001249void LogReader::SetEndTime(std::string end_time) {
1250 if (end_time.empty()) {
1251 SetEndTime(realtime_clock::max_time);
1252 } else {
1253 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1254 aos::realtime_clock::FromString(end_time);
1255 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1256 << "'. Expected a date in the format of "
1257 "2021-01-15_15-30-35.000000000.";
1258 SetEndTime(*parsed_end_time);
1259 }
1260}
1261
1262void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1263 end_time_ = end_time;
1264}
1265
1266void LogReader::SetStartTime(std::string start_time) {
1267 if (start_time.empty()) {
1268 SetStartTime(realtime_clock::min_time);
1269 } else {
1270 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1271 aos::realtime_clock::FromString(start_time);
1272 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1273 << "'. Expected a date in the format of "
1274 "2021-01-15_15-30-35.000000000.";
1275 SetStartTime(*parsed_start_time);
1276 }
1277}
1278
1279void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1280 start_time_ = start_time;
1281}
1282
Austin Schuhe309d2a2019-11-29 13:25:21 -08001283void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001284 // Make sure that things get destroyed in the correct order, rather than
1285 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001286 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001287 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001288 }
Austin Schuh92547522019-12-28 14:33:43 -08001289
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001290 event_loop_factory_unique_ptr_.reset();
1291 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001292}
1293
James Kuszmaul53da7f32022-09-11 11:11:55 -07001294namespace {
1295// Checks if the specified channel name/type exists in the config and, depending
1296// on the value of conflict_handling, calls conflict_handler or just dies.
1297template <typename F>
1298void CheckAndHandleRemapConflict(std::string_view new_name,
1299 std::string_view new_type,
1300 const Configuration *config,
1301 LogReader::RemapConflict conflict_handling,
1302 F conflict_handler) {
1303 const Channel *existing_channel =
1304 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1305 if (existing_channel != nullptr) {
1306 switch (conflict_handling) {
1307 case LogReader::RemapConflict::kDisallow:
1308 LOG(FATAL)
1309 << "Channel "
1310 << configuration::StrippedChannelToString(existing_channel)
1311 << " is already used--you can't remap a logged channel to it.";
1312 break;
1313 case LogReader::RemapConflict::kCascade:
1314 LOG(INFO) << "Automatically remapping "
1315 << configuration::StrippedChannelToString(existing_channel)
1316 << " to avoid conflicts.";
1317 conflict_handler();
1318 break;
1319 }
1320 }
1321}
1322} // namespace
1323
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001324void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001325 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001326 std::string_view new_type,
1327 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001328 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1329 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001330}
1331
Austin Schuh01b4c352020-09-21 23:09:39 -07001332void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1333 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001334 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001335 std::string_view new_type,
1336 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001337 if (node != nullptr) {
1338 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1339 }
1340 if (replay_channels_ != nullptr) {
1341 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1342 std::make_pair(std::string{name}, std::string{type})) !=
1343 replay_channels_->end())
1344 << "Attempted to remap channel " << name << " " << type
1345 << " which is not included in the replay channels passed to LogReader.";
1346 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001347 const Channel *remapped_channel =
1348 configuration::GetChannel(logged_configuration(), name, type, "", node);
1349 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1350 << "\", \"type\": \"" << type << "\"}";
1351 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1352 << "\"}";
1353 VLOG(1) << "Remapped "
1354 << aos::configuration::StrippedChannelToString(remapped_channel);
1355
1356 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1357 // we want it to degrade if the heuristics fail to just work.
1358 //
1359 // The easiest way to do this is going to be incredibly specific and verbose.
1360 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1361 // /original/0/spray. Then, create a map from /original/spray to
1362 // /original/0/spray for just the type we were asked for.
1363 if (name != remapped_channel->name()->string_view()) {
1364 MapT new_map;
1365 new_map.match = std::make_unique<ChannelT>();
1366 new_map.match->name = absl::StrCat(add_prefix, name);
1367 new_map.match->type = type;
1368 if (node != nullptr) {
1369 new_map.match->source_node = node->name()->str();
1370 }
1371 new_map.rename = std::make_unique<ChannelT>();
1372 new_map.rename->name =
1373 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1374 maps_.emplace_back(std::move(new_map));
1375 }
1376
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001377 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001378 const size_t channel_index =
1379 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1380 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1381 << "Already remapped channel "
1382 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001383
1384 RemappedChannel remapped_channel_struct;
1385 remapped_channel_struct.remapped_name =
1386 std::string(add_prefix) +
1387 std::string(remapped_channel->name()->string_view());
1388 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001389 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1390 CheckAndHandleRemapConflict(
1391 remapped_channel_struct.remapped_name, remapped_type,
1392 remapped_configuration_, conflict_handling,
1393 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1394 conflict_handling]() {
1395 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1396 node, add_prefix, "", conflict_handling);
1397 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001398 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001399 MakeRemappedConfig();
1400}
1401
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001402void LogReader::RenameLoggedChannel(const std::string_view name,
1403 const std::string_view type,
1404 const std::string_view new_name,
1405 const std::vector<MapT> &add_maps) {
1406 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1407}
1408
1409void LogReader::RenameLoggedChannel(const std::string_view name,
1410 const std::string_view type,
1411 const Node *const node,
1412 const std::string_view new_name,
1413 const std::vector<MapT> &add_maps) {
1414 if (node != nullptr) {
1415 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1416 }
1417 // First find the channel and rename it.
1418 const Channel *remapped_channel =
1419 configuration::GetChannel(logged_configuration(), name, type, "", node);
1420 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1421 << "\", \"type\": \"" << type << "\"}";
1422 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1423 << "\"}";
1424 VLOG(1) << "Remapped "
1425 << aos::configuration::StrippedChannelToString(remapped_channel);
1426
1427 const size_t channel_index =
1428 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1429 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1430 << "Already remapped channel "
1431 << configuration::CleanedChannelToString(remapped_channel);
1432
1433 RemappedChannel remapped_channel_struct;
1434 remapped_channel_struct.remapped_name = new_name;
1435 remapped_channel_struct.new_type.clear();
1436 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1437
1438 // Then add any provided maps.
1439 for (const MapT &map : add_maps) {
1440 maps_.push_back(map);
1441 }
1442
1443 // Finally rewrite the config.
1444 MakeRemappedConfig();
1445}
1446
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001447void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001448 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001449 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001450 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001451 << ": Can't change the mapping after the events are scheduled.";
1452 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001453 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001454
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001455 // If no remapping occurred and we are using the original config, then there
1456 // is nothing interesting to do here.
1457 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001458 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001459 return;
1460 }
1461 // Config to copy Channel definitions from. Use the specified
1462 // replay_configuration_ if it has been provided.
1463 const Configuration *const base_config = replay_configuration_ == nullptr
1464 ? logged_configuration()
1465 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001466
1467 // Create a config with all the channels, but un-sorted/merged. Collect up
1468 // the schemas while we do this. Call MergeConfiguration to sort everything,
1469 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001470
1471 // This is the builder that we use for the config containing all the new
1472 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001473 flatbuffers::FlatBufferBuilder fbb;
1474 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001475 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001476
1477 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1478 << ": Merging logic needs to be updated when the number of channel "
1479 "fields changes.";
1480
1481 // List of schemas.
1482 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1483 // Make sure our new RemoteMessage schema is in there for old logs without it.
1484 schema_map.insert(std::make_pair(
1485 RemoteMessage::GetFullyQualifiedName(),
1486 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1487 message_bridge::RemoteMessageSchema()))));
1488
1489 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001490 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001491 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001492 base_config, logged_configuration()->channels()->Get(pair.first), "",
1493 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001494 channel_offsets.emplace_back(
1495 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001496
1497 if (c->has_destination_nodes()) {
1498 for (const Connection *connection : *c->destination_nodes()) {
1499 switch (connection->timestamp_logger()) {
1500 case LoggerConfig::LOCAL_LOGGER:
1501 case LoggerConfig::NOT_LOGGED:
1502 // There is no timestamp channel associated with this, so ignore it.
1503 break;
1504
1505 case LoggerConfig::REMOTE_LOGGER:
1506 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1507 // We want to make a split timestamp channel regardless of what type
1508 // of log this used to be. No sense propagating the single
1509 // timestamp channel.
1510
1511 CHECK(connection->has_timestamp_logger_nodes());
1512 for (const flatbuffers::String *timestamp_logger_node :
1513 *connection->timestamp_logger_nodes()) {
1514 const Node *node = configuration::GetNode(
1515 logged_configuration(), timestamp_logger_node->string_view());
1516 message_bridge::ChannelTimestampFinder finder(
1517 logged_configuration(), "log_reader", node);
1518
1519 // We are assuming here that all the maps are setup correctly to
1520 // handle arbitrary timestamps. Apply the maps for this node to
1521 // see what name this ends up with.
1522 std::string name = finder.SplitChannelName(
1523 pair.second.remapped_name, c->type()->str(), connection);
1524 std::string unmapped_name = name;
1525 configuration::HandleMaps(logged_configuration()->maps(), &name,
1526 "aos.message_bridge.RemoteMessage",
1527 node);
1528 CHECK_NE(name, unmapped_name)
1529 << ": Remote timestamp channel was not remapped, this is "
1530 "very fishy";
1531 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1532 fbb.CreateString(name);
1533 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1534 fbb.CreateString("aos.message_bridge.RemoteMessage");
1535 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1536 fbb.CreateString(timestamp_logger_node->string_view());
1537
1538 // Now, build a channel. Don't log it, 2 senders, and match the
1539 // source frequency.
1540 Channel::Builder channel_builder(fbb);
1541 channel_builder.add_name(channel_name_offset);
1542 channel_builder.add_type(channel_type_offset);
1543 channel_builder.add_source_node(source_node_offset);
1544 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1545 channel_builder.add_num_senders(2);
1546 if (c->has_frequency()) {
1547 channel_builder.add_frequency(c->frequency());
1548 }
1549 channel_offsets.emplace_back(channel_builder.Finish());
1550 }
1551 break;
1552 }
1553 }
1554 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001555 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001556
Austin Schuh0de30f32020-12-06 12:44:28 -08001557 // Now reconstruct the original channels, translating types as needed
1558 for (const Channel *c : *base_config->channels()) {
1559 // Search for a mapping channel.
1560 std::string_view new_type = "";
1561 for (auto &pair : remapped_channels_) {
1562 const Channel *const remapped_channel =
1563 logged_configuration()->channels()->Get(pair.first);
1564 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1565 remapped_channel->type()->string_view() == c->type()->string_view()) {
1566 new_type = pair.second.new_type;
1567 break;
1568 }
1569 }
1570
1571 // Copy everything over.
1572 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1573
1574 // Add the schema if it doesn't exist.
1575 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1576 CHECK(c->has_schema());
1577 schema_map.insert(std::make_pair(c->type()->string_view(),
1578 RecursiveCopyFlatBuffer(c->schema())));
1579 }
1580 }
1581
1582 // The MergeConfiguration API takes a vector, not a map. Convert.
1583 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1584 while (!schema_map.empty()) {
1585 schemas.emplace_back(std::move(schema_map.begin()->second));
1586 schema_map.erase(schema_map.begin());
1587 }
1588
1589 // Create the Configuration containing the new channels that we want to add.
1590 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1591 channels_offset =
1592 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1593
1594 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001595 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001596 if (base_config->maps()) {
1597 for (const Map *map : *base_config->maps()) {
1598 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1599 }
1600 }
1601
1602 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001603 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001604 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001605 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001606 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001607 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1608 if (!map.match->type.empty()) {
1609 match_type_offset = fbb.CreateString(map.match->type);
1610 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001611 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1612 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001613 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001614 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001615 CHECK(!map.rename->name.empty());
1616 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1617 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001618 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001619 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001620 if (!match_type_offset.IsNull()) {
1621 match_builder.add_type(match_type_offset);
1622 }
1623 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001624 match_builder.add_source_node(match_source_node_offset);
1625 }
1626 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1627
Austin Schuh0de30f32020-12-06 12:44:28 -08001628 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001629 rename_builder.add_name(rename_name_offset);
1630 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1631
Austin Schuh0de30f32020-12-06 12:44:28 -08001632 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001633 map_builder.add_match(match_offset);
1634 map_builder.add_rename(rename_offset);
1635 map_offsets.emplace_back(map_builder.Finish());
1636 }
1637
Austin Schuh0de30f32020-12-06 12:44:28 -08001638 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1639 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001640
Austin Schuh0de30f32020-12-06 12:44:28 -08001641 // And copy everything else over.
1642 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1643 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1644
1645 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1646 applications_offset =
1647 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1648
1649 // Now insert everything else in unmodified.
1650 ConfigurationBuilder configuration_builder(fbb);
1651 if (!channels_offset.IsNull()) {
1652 configuration_builder.add_channels(channels_offset);
1653 }
1654 if (!maps_offsets.IsNull()) {
1655 configuration_builder.add_maps(maps_offsets);
1656 }
1657 if (!nodes_offset.IsNull()) {
1658 configuration_builder.add_nodes(nodes_offset);
1659 }
1660 if (!applications_offset.IsNull()) {
1661 configuration_builder.add_applications(applications_offset);
1662 }
1663
1664 if (base_config->has_channel_storage_duration()) {
1665 configuration_builder.add_channel_storage_duration(
1666 base_config->channel_storage_duration());
1667 }
1668
1669 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1670 << ": Merging logic needs to be updated when the number of configuration "
1671 "fields changes.";
1672
1673 fbb.Finish(configuration_builder.Finish());
1674
1675 // Clean it up and return it! By using MergeConfiguration here, we'll
1676 // actually get a deduplicated config for free too.
1677 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1678 configuration::MergeConfiguration(
1679 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1680
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001681 remapped_configuration_buffer_ =
1682 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001683 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001684
1685 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001686
1687 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001688}
1689
Naman Guptacf6d4422023-03-01 11:41:00 -08001690std::unique_ptr<const ReplayChannelIndices>
1691LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001692 if (replay_channels_ == nullptr) {
1693 return nullptr;
1694 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001695 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1696 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001697 for (auto const &channel : *replay_channels_) {
1698 const Channel *ch = configuration::GetChannel(
1699 logged_configuration(), channel.first, channel.second, "", node);
1700 if (ch == nullptr) {
1701 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1702 << " not found in configuration for node: "
1703 << node->name()->string_view() << " Skipping ...";
1704 continue;
1705 }
1706 const size_t channel_index =
1707 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001708 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001709 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001710 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1711 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001712 }
1713}
1714
Austin Schuh1c227352021-09-17 12:53:54 -07001715std::vector<const Channel *> LogReader::RemappedChannels() const {
1716 std::vector<const Channel *> result;
1717 result.reserve(remapped_channels_.size());
1718 for (auto &pair : remapped_channels_) {
1719 const Channel *const logged_channel =
1720 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1721
1722 auto channel_iterator = std::lower_bound(
1723 remapped_configuration_->channels()->cbegin(),
1724 remapped_configuration_->channels()->cend(),
1725 std::make_pair(std::string_view(pair.second.remapped_name),
1726 logged_channel->type()->string_view()),
1727 CompareChannels);
1728
1729 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1730 CHECK(EqualsChannels(
1731 *channel_iterator,
1732 std::make_pair(std::string_view(pair.second.remapped_name),
1733 logged_channel->type()->string_view())));
1734 result.push_back(*channel_iterator);
1735 }
1736 return result;
1737}
1738
Austin Schuh6f3babe2020-01-26 20:34:50 -08001739const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001740 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001741 const Channel *channel) {
1742 std::string_view channel_name = channel->name()->string_view();
1743 std::string_view channel_type = channel->type()->string_view();
1744 const int channel_index =
1745 configuration::ChannelIndex(logged_configuration(), channel);
1746 // If the channel is remapped, find the correct channel name to use.
1747 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001748 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001749 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001750 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001751 }
1752
Austin Schuhee711052020-08-24 16:06:09 -07001753 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001754 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001755 configuration(), channel_name, channel_type,
1756 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001757
1758 CHECK(remapped_channel != nullptr)
1759 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1760 << channel_type << "\"} because it is not in the provided configuration.";
1761
1762 return remapped_channel;
1763}
1764
James Kuszmaul09632422022-05-25 15:56:19 -07001765LogReader::State::State(
1766 std::unique_ptr<TimestampMapper> timestamp_mapper,
1767 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001768 std::function<void()> notice_realtime_end, const Node *node,
1769 LogReader::State::ThreadedBuffering threading,
Naman Guptacf6d4422023-03-01 11:41:00 -08001770 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices)
James Kuszmaul09632422022-05-25 15:56:19 -07001771 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001772 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001773 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001774 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001775 threading_(threading),
Naman Guptacf6d4422023-03-01 11:41:00 -08001776 replay_channel_indices_(std::move(replay_channel_indices)) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001777 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1778 // with this node. If there are no log parts for the node, there will be no
1779 // log data, and so we do not need to worry about the replay channel filters.
1780 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001781 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001782 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001783 const TimestampedMessage &message) -> bool {
1784 auto const begin = filter->cbegin();
1785 auto const end = filter->cend();
1786 // TODO: benchmark strategies for channel_index matching
1787 return std::binary_search(begin, end, message.channel_index);
1788 });
1789 }
1790}
Austin Schuh287d43d2020-12-04 20:19:33 -08001791
1792void LogReader::State::AddPeer(State *peer) {
1793 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1794 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1795 }
1796}
Austin Schuh858c9f32020-08-31 16:56:12 -07001797
Austin Schuh58646e22021-08-23 23:51:46 -07001798void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001799 NodeEventLoopFactory *node_event_loop_factory,
1800 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001801 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001802 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001803}
1804
1805void LogReader::State::SetChannelCount(size_t count) {
1806 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001807 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001808 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001809 channel_source_state_.resize(count);
1810 factory_channel_index_.resize(count);
1811 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001812}
1813
Austin Schuh58646e22021-08-23 23:51:46 -07001814void LogReader::State::SetRemoteTimestampSender(
1815 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1816 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1817}
1818
Austin Schuh858c9f32020-08-31 16:56:12 -07001819void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001820 size_t logged_channel_index, size_t factory_channel_index,
1821 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001822 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1823 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001824 channels_[logged_channel_index] = std::move(sender);
1825 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001826 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001827
Austin Schuh58646e22021-08-23 23:51:46 -07001828 if (is_forwarded) {
1829 queue_index_map_[logged_channel_index] =
1830 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001831 }
1832
1833 factory_channel_index_[logged_channel_index] = factory_channel_index;
1834}
1835
James Kuszmaula16a7912022-06-17 10:58:12 -07001836void LogReader::State::TrackMessageSendTiming(
1837 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1838 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1839 return;
1840 }
1841
1842 timing::MessageTimingT sample;
1843 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1844 sender.channel());
1845 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1846 sample.actual_send_time =
1847 sender.monotonic_sent_time().time_since_epoch().count();
1848 sample.send_time_error = aos::time::DurationInSeconds(
1849 expected_send_time - sender.monotonic_sent_time());
1850 send_timings_.push_back(sample);
1851
1852 // Somewhat arbitrarily send out timing information in batches of 100. No need
1853 // to create excessive overhead in regenerated logfiles.
1854 // TODO(james): The overhead may be fine.
1855 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1856 CHECK(timing_statistics_sender_.valid());
1857 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1858 SendMessageTimings();
1859 }
1860}
1861
1862void LogReader::State::SendMessageTimings() {
1863 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1864 return;
1865 }
1866 auto builder = timing_statistics_sender_.MakeBuilder();
1867 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1868 for (const auto &timing : send_timings_) {
1869 timing_offsets.push_back(
1870 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1871 }
1872 send_timings_.clear();
1873 flatbuffers::Offset<
1874 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1875 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1876 timing::ReplayTiming::Builder timing_builder =
1877 builder.MakeBuilder<timing::ReplayTiming>();
1878 timing_builder.add_messages(timings_offset);
1879 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1880}
1881
Austin Schuh287d43d2020-12-04 20:19:33 -08001882bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1883 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001884 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001885 uint32_t remote_queue_index = 0xffffffff;
1886
Austin Schuh287d43d2020-12-04 20:19:33 -08001887 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001888 State *source_state =
1889 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001890 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001891 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001892 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001893
Austin Schuh9942bae2021-01-07 22:06:44 -08001894 struct SentTimestamp {
1895 monotonic_clock::time_point monotonic_event_time;
1896 uint32_t queue_index;
1897 } search;
1898
Austin Schuh58646e22021-08-23 23:51:46 -07001899 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1900 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001901 search.monotonic_event_time =
1902 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001903 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001904
1905 // Find the sent time if available.
1906 auto element = std::lower_bound(
1907 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001908 [](ContiguousSentTimestamp a, SentTimestamp b) {
1909 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001910 return true;
1911 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001912 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001913 return false;
1914 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001915
1916 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001917 return true;
1918 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001919 if (a.starting_queue_index >= b.queue_index) {
1920 return false;
1921 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001922
Austin Schuh9942bae2021-01-07 22:06:44 -08001923 // If it isn't clearly below or above, it is below. Since we return
1924 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001925 return false;
1926 });
1927
1928 // TODO(austin): Be a bit more principled here, but we will want to do that
1929 // after the logger rewrite. We hit this when one node finishes, but the
1930 // other node isn't done yet. So there is no send time, but there is a
1931 // receive time.
1932 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001933 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1934 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001935
1936 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001937 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001938 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001939 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001940 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001941 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001942 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001943 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001944
Austin Schuh58646e22021-08-23 23:51:46 -07001945 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001946 element->actual_queue_index -
1947 element->starting_queue_index;
1948 } else {
1949 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001950 }
Austin Schuh58646e22021-08-23 23:51:46 -07001951 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1952 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001953 }
1954
James Kuszmaul09632422022-05-25 15:56:19 -07001955 if (event_loop_factory_ != nullptr &&
1956 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1957 multinode_filters_ != nullptr) {
1958 // Sanity check that we are using consistent boot uuids.
1959 State *source_state =
1960 channel_source_state_[timestamped_message.channel_index];
1961 CHECK_EQ(multinode_filters_->boot_uuid(
1962 configuration::GetNodeIndex(event_loop_->configuration(),
1963 source_state->node()),
1964 timestamped_message.monotonic_remote_time.boot),
1965 CHECK_NOTNULL(
1966 CHECK_NOTNULL(
1967 channel_source_state_[timestamped_message.channel_index])
1968 ->event_loop_)
1969 ->boot_uuid());
1970 }
1971
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001972 // Send! Use the replayed queue index here instead of the logged queue index
1973 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001974 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001975 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001976 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001977 timestamped_message.realtime_remote_time, remote_queue_index,
1978 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001979 ? CHECK_NOTNULL(multinode_filters_)
1980 ->boot_uuid(configuration::GetNodeIndex(
1981 event_loop_->configuration(),
1982 channel_source_state_[timestamped_message
1983 .channel_index]
1984 ->node()),
1985 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001986 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001987 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001988 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1989 timestamped_message.monotonic_event_time.time) {
1990 // Only track errors for non-fetched messages.
1991 TrackMessageSendTiming(
1992 *sender,
1993 timestamped_message.monotonic_event_time.time + clock_offset());
1994 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001995
Austin Schuh287d43d2020-12-04 20:19:33 -08001996 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001997 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001998 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1999 // Nothing here, start a range with 0 length.
2000 ContiguousSentTimestamp timestamp;
2001 timestamp.starting_monotonic_event_time =
2002 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002003 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002004 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002005 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002006 timestamp.actual_queue_index = sender->sent_queue_index();
2007 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2008 timestamp);
2009 } else {
2010 // We've got something. See if the next timestamp is still contiguous. If
2011 // so, grow it.
2012 ContiguousSentTimestamp *back =
2013 &queue_index_map_[timestamped_message.channel_index]->back();
2014 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002015 (timestamped_message.queue_index.index -
2016 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002017 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002018 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002019 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002020 } else {
2021 // Otherwise, make a new one.
2022 ContiguousSentTimestamp timestamp;
2023 timestamp.starting_monotonic_event_time =
2024 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002025 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002026 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002027 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002028 timestamp.actual_queue_index = sender->sent_queue_index();
2029 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2030 timestamp);
2031 }
2032 }
2033
2034 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2035 // queue index diverge a couple of elements, which would be a very small
2036 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002037 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2038 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002039 // TODO(james): Currently, If running replay against a single event loop,
2040 // remote timestamps will not get replayed because this code-path only
2041 // gets triggered on the event loop that receives the forwarded message
2042 // that the timestamps correspond to. This code, as written, also doesn't
2043 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002044 State *source_state =
2045 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2046
Austin Schuh969cd602021-01-03 00:09:45 -08002047 flatbuffers::FlatBufferBuilder fbb;
2048 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002049 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2050 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002051
Austin Schuh969cd602021-01-03 00:09:45 -08002052 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002053
2054 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002055 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002056
2057 // Swap the remote and sent metrics. They are from the sender's
2058 // perspective, not the receiver's perspective.
2059 message_header_builder.add_monotonic_sent_time(
2060 sender->monotonic_sent_time().time_since_epoch().count());
2061 message_header_builder.add_realtime_sent_time(
2062 sender->realtime_sent_time().time_since_epoch().count());
2063 message_header_builder.add_queue_index(sender->sent_queue_index());
2064
Austin Schuh58646e22021-08-23 23:51:46 -07002065 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2066 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002067 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002068 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2069 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002070 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002071 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002072
2073 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002074 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002075
Austin Schuh969cd602021-01-03 00:09:45 -08002076 fbb.Finish(message_header_builder.Finish());
2077
2078 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2079 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002080 timestamped_message.monotonic_timestamp_time,
2081 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002082 }
2083
2084 return true;
2085}
2086
Austin Schuh969cd602021-01-03 00:09:45 -08002087LogReader::RemoteMessageSender::RemoteMessageSender(
2088 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2089 : event_loop_(event_loop),
2090 sender_(std::move(sender)),
2091 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2092
2093void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2094 if (remote_timestamps_.empty()) {
2095 CHECK_NOTNULL(timer_);
2096 timer_->Disable();
2097 scheduled_time_ = monotonic_clock::min_time;
2098 return;
2099 }
2100
2101 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2102 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002103 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002104 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002105 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2106 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002107 }
2108}
2109
2110void LogReader::RemoteMessageSender::Send(
2111 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002112 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002113 // There are 2 variants of logs.
2114 // 1) Logs without monotonic_timestamp_time
2115 // 2) Logs with monotonic_timestamp_time
2116 //
2117 // As of Jan 2021, we shouldn't have any more logs without
2118 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2119 // the effort of saving.
2120 //
2121 // This gives us 3 cases, 2 of which are undistinguishable.
2122 // 1) Old log without monotonic_timestamp_time.
2123 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2124 // remotely so we actually have monotonic_timestamp_time.
2125 // 3) New log, but the timestamp was logged on the node receiving the message
2126 // so there is no monotonic_timestamp_time.
2127 //
2128 // Our goal when replaying is to accurately reproduce the state of the world
2129 // present when logging. If a timestamp wasn't sent back across the network,
2130 // we shouldn't replay one back across the network.
2131 //
2132 // Given that we don't really care about 1, we can use the presence of the
2133 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2134 // monotonic_timestamp_time, this means the message was logged locally and
2135 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002136 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002137 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002138 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002139
Austin Schuh58646e22021-08-23 23:51:46 -07002140 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2141
Austin Schuhc41d6a82021-07-16 14:49:23 -07002142 remote_timestamps_.emplace(
2143 std::upper_bound(
2144 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002145 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002146 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2147 const Timestamp &timestamp) {
2148 return monotonic_timestamp_time <
2149 timestamp.monotonic_timestamp_time;
2150 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002151 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002152 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002153}
2154
2155void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002156 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2157 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002158 CHECK(!remote_timestamps_.empty());
2159
2160 // Send out all timestamps at the currently scheduled time.
2161 while (remote_timestamps_.front().monotonic_timestamp_time ==
2162 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002163 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2164 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002165 remote_timestamps_.pop_front();
2166 if (remote_timestamps_.empty()) {
2167 break;
2168 }
2169 }
2170 scheduled_time_ = monotonic_clock::min_time;
2171
2172 ScheduleTimestamp();
2173}
2174
2175LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002176 const Channel *channel, const Connection *connection) {
2177 message_bridge::ChannelTimestampFinder finder(event_loop_);
2178 // Look at any pre-created channel/connection pairs.
2179 {
2180 auto it =
2181 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2182 if (it != channel_timestamp_loggers_.end()) {
2183 return it->second.get();
2184 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002185 }
2186
Austin Schuh61e973f2021-02-21 21:43:56 -08002187 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2188 // to.
2189 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2190
2191 {
2192 // See if that has been created before. If so, cache it in
2193 // channel_timestamp_loggers_ and return.
2194 auto it = timestamp_loggers_.find(timestamp_channel);
2195 if (it != timestamp_loggers_.end()) {
2196 CHECK(channel_timestamp_loggers_
2197 .try_emplace(std::make_pair(channel, connection), it->second)
2198 .second);
2199 return it->second.get();
2200 }
2201 }
2202
2203 // Otherwise, make a sender, save it, and cache it.
2204 auto result = channel_timestamp_loggers_.try_emplace(
2205 std::make_pair(channel, connection),
2206 std::make_shared<RemoteMessageSender>(
2207 event_loop()->MakeSender<RemoteMessage>(
2208 timestamp_channel->name()->string_view()),
2209 event_loop()));
2210
2211 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2212 .second);
2213 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002214}
2215
Austin Schuhdda74ec2021-01-03 19:30:37 -08002216TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002217 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002218 if (message_queuer_.has_value()) {
2219 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2220 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2221 message_queuer_->SetState(
2222 message.value().monotonic_event_time +
2223 std::chrono::duration_cast<std::chrono::nanoseconds>(
2224 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2225 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002226 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002227 CHECK(timestamp_mapper_ != nullptr);
2228 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2229 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002230
James Kuszmaula16a7912022-06-17 10:58:12 -07002231 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002232
James Kuszmaula16a7912022-06-17 10:58:12 -07002233 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2234 << result.monotonic_event_time;
2235 timestamp_mapper_->PopFront();
2236 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002237
James Kuszmaula16a7912022-06-17 10:58:12 -07002238 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002239
James Kuszmaula16a7912022-06-17 10:58:12 -07002240 VLOG(1) << "Popped " << result
2241 << configuration::CleanedChannelToString(
2242 event_loop_->configuration()->channels()->Get(
2243 factory_channel_index_[result.channel_index]));
2244 return result;
2245 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002246}
2247
James Kuszmaula16a7912022-06-17 10:58:12 -07002248BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2249 if (!message_queuer_.has_value()) {
2250 return SingleThreadedOldestMessageTime();
2251 }
2252 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2253 if (!message.has_value()) {
2254 return BootTimestamp::max_time();
2255 }
2256 if (message.value().monotonic_event_time.boot == boot_count()) {
2257 ObserveNextMessage(message.value().monotonic_event_time.time,
2258 message.value().realtime_event_time);
2259 }
2260 return message.value().monotonic_event_time;
2261}
2262
2263BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2264 CHECK(!message_queuer_.has_value())
2265 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2266 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002267 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002268 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002269 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002270 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2271 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002272 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002273 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002274 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002275 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002276 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2277 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2278 result_ptr->realtime_event_time);
2279 }
Austin Schuh58646e22021-08-23 23:51:46 -07002280 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002281}
2282
2283void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002284 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002285
Austin Schuhe639ea12021-01-25 13:00:22 -08002286 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2287 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002288}
2289
2290void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002291 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002292 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002293 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002294 for (size_t i = 0; i < channels_.size(); ++i) {
2295 channels_[i].reset();
2296 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002297 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002298 channel_timestamp_loggers_.clear();
2299 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002300 event_loop_unique_ptr_.reset();
2301 event_loop_ = nullptr;
2302 timer_handler_ = nullptr;
2303 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002304 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002305}
2306
Austin Schuhe33c08d2022-02-03 18:15:21 -08002307void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2308 if (start_time != realtime_clock::min_time) {
2309 start_event_notifier_ = std::make_unique<EventNotifier>(
2310 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2311 }
2312}
2313
2314void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2315 if (end_time != realtime_clock::max_time) {
2316 end_event_notifier_ = std::make_unique<EventNotifier>(
2317 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2318 }
2319}
2320
2321void LogReader::State::ObserveNextMessage(
2322 monotonic_clock::time_point monotonic_event,
2323 realtime_clock::time_point realtime_event) {
2324 if (start_event_notifier_) {
2325 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2326 }
2327 if (end_event_notifier_) {
2328 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2329 }
2330}
2331
2332void LogReader::State::ClearTimeFlags() {
2333 start_event_notifier_.reset();
2334 end_event_notifier_.reset();
2335}
2336
2337void LogReader::State::NotifyLogfileStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002338 // If the start_event_notifier_ is set, that means that a realtime start time
2339 // was set manually; when the override is set, we want to delay any startup
2340 // handlers that would've happened before requested start time until that
2341 // start time.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002342 if (start_event_notifier_) {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002343 // Only call OnStart() if the start time for this node (realtime_start_time())
Austin Schuhe33c08d2022-02-03 18:15:21 -08002344 if (start_event_notifier_->realtime_event_time() >
2345 realtime_start_time(boot_count())) {
2346 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2347 << " > " << realtime_start_time(boot_count());
2348 return;
2349 }
2350 }
2351 if (found_last_message_) {
2352 VLOG(1) << "Last message already found, bailing";
2353 return;
2354 }
2355 RunOnStart();
2356}
2357
2358void LogReader::State::NotifyFlagStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002359 // Should only be called if start_event_notifier_ has been set (which happens
2360 // as part of setting an explicit start time); only call the startup functions
2361 // that occurred *before* the start flag value.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002362 if (start_event_notifier_->realtime_event_time() >=
2363 realtime_start_time(boot_count())) {
2364 RunOnStart();
2365 }
2366}
2367
2368void LogReader::State::NotifyLogfileEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002369 // Don't execute the OnEnd handlers if the logfile was ended artifically
2370 // early.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002371 if (found_last_message_) {
2372 return;
2373 }
2374
James Kuszmaul82c3b512023-07-08 20:25:41 -07002375 // Ensure that we only call OnEnd() if OnStart() was already called for this
2376 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002377 if (!stopped_ && started_) {
2378 RunOnEnd();
2379 }
2380}
2381
2382void LogReader::State::NotifyFlagEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002383 // Ensure that we only call OnEnd() if OnStart() was already called for this
2384 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002385 if (!stopped_ && started_) {
2386 RunOnEnd();
2387 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002388 CHECK(notice_realtime_end_);
2389 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002390 }
2391}
2392
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002393void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002394 if (node_event_loop_factory_ == nullptr) {
2395 // If not running with simulated event loop, set the monotonic clock
2396 // offset.
2397 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2398
2399 if (start_event_notifier_) {
2400 start_event_notifier_->SetClockOffset(clock_offset_);
2401 }
2402 if (end_event_notifier_) {
2403 end_event_notifier_->SetClockOffset(clock_offset_);
2404 }
2405 }
2406}
2407
James Kuszmaulb67409b2022-06-20 16:25:03 -07002408void LogReader::SetRealtimeReplayRate(double replay_rate) {
2409 CHECK(event_loop_factory_ != nullptr)
2410 << ": Can't set replay rate without an event loop factory (have you "
2411 "called Register()?).";
2412 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2413}
2414
James Kuszmaulb11a1502022-07-01 16:02:25 -07002415void LogReader::NoticeRealtimeEnd() {
2416 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2417 --live_nodes_with_realtime_time_end_;
2418 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2419 event_loop_factory_ != nullptr) {
2420 event_loop_factory_->Exit();
2421 }
2422}
2423
Austin Schuhe309d2a2019-11-29 13:25:21 -08002424} // namespace logger
2425} // namespace aos