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