blob: 75a53e1cfa6337e065f98a1115300fbc6a798f01 [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
Austin Schuhaf8a0d32023-05-03 09:53:06 -07003#include <dirent.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08004#include <fcntl.h>
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08008
Tyler Chatowbf0609c2021-07-31 16:13:27 -07009#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -080010#include <vector>
11
Austin Schuh2f8fd752020-09-01 22:38:28 -070012#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080013#include "absl/types/span.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070014#include "flatbuffers/flatbuffers.h"
15#include "openssl/sha.h"
16
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070018#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070019#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080020#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080021#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070022#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080023#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080024#include "aos/network/remote_message_generated.h"
25#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080026#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080027#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070029#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070030#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080031
Austin Schuh15649d62019-12-28 16:36:38 -080032DEFINE_bool(skip_missing_forwarding_entries, false,
33 "If true, drop any forwarding entries with missing data. If "
34 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080035
Austin Schuh0ca1fd32020-12-18 22:53:05 -080036DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080037
Austin Schuh2f8fd752020-09-01 22:38:28 -070038DEFINE_bool(skip_order_validation, false,
39 "If true, ignore any out of orderness in replay");
40
Austin Schuhf0688662020-12-19 15:37:45 -080041DEFINE_double(
42 time_estimation_buffer_seconds, 2.0,
43 "The time to buffer ahead in the log file to accurately reconstruct time.");
44
Austin Schuhe33c08d2022-02-03 18:15:21 -080045DEFINE_string(
46 start_time, "",
47 "If set, start at this point in time in the log on the realtime clock.");
48DEFINE_string(
49 end_time, "",
50 "If set, end at this point in time in the log on the realtime clock.");
51
James Kuszmaul09632422022-05-25 15:56:19 -070052DEFINE_bool(drop_realtime_messages_before_start, false,
53 "If set, will drop any messages sent before the start of the "
54 "logfile in realtime replay. Setting this guarantees consistency "
55 "in timing with the original logfile, but means that you lose "
56 "access to fetched low-frequency messages.");
57
James Kuszmaula16a7912022-06-17 10:58:12 -070058DEFINE_double(
59 threaded_look_ahead_seconds, 2.0,
60 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
61 "Can validly be zero, but higher values are encouraged for realtime replay "
62 "in order to prevent the replay from ever having to block on waiting for "
63 "the reader to find the next message.");
64
Austin Schuhe309d2a2019-11-29 13:25:21 -080065namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070066namespace configuration {
67// We don't really want to expose this publicly, but log reader doesn't really
68// want to re-implement it.
69void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
70 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070071} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080072namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070073namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080074
Austin Schuh1c227352021-09-17 12:53:54 -070075bool CompareChannels(const Channel *c,
76 ::std::pair<std::string_view, std::string_view> p) {
77 int name_compare = c->name()->string_view().compare(p.first);
78 if (name_compare == 0) {
79 return c->type()->string_view() < p.second;
80 } else if (name_compare < 0) {
81 return true;
82 } else {
83 return false;
84 }
85}
86
87bool EqualsChannels(const Channel *c,
88 ::std::pair<std::string_view, std::string_view> p) {
89 return c->name()->string_view() == p.first &&
90 c->type()->string_view() == p.second;
91}
92
Austin Schuh0de30f32020-12-06 12:44:28 -080093// Copies the channel, removing the schema as we go. If new_name is provided,
94// it is used instead of the name inside the channel. If new_type is provided,
95// it is used instead of the type in the channel.
96flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
97 std::string_view new_name,
98 std::string_view new_type,
99 flatbuffers::FlatBufferBuilder *fbb) {
100 flatbuffers::Offset<flatbuffers::String> name_offset =
101 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
102 : new_name);
103 flatbuffers::Offset<flatbuffers::String> type_offset =
104 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
105 flatbuffers::Offset<flatbuffers::String> source_node_offset =
106 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
107 : 0;
108
109 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
110 destination_nodes_offset =
111 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
112
113 flatbuffers::Offset<
114 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
115 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
116
117 Channel::Builder channel_builder(*fbb);
118 channel_builder.add_name(name_offset);
119 channel_builder.add_type(type_offset);
120 if (c->has_frequency()) {
121 channel_builder.add_frequency(c->frequency());
122 }
123 if (c->has_max_size()) {
124 channel_builder.add_max_size(c->max_size());
125 }
126 if (c->has_num_senders()) {
127 channel_builder.add_num_senders(c->num_senders());
128 }
129 if (c->has_num_watchers()) {
130 channel_builder.add_num_watchers(c->num_watchers());
131 }
132 if (!source_node_offset.IsNull()) {
133 channel_builder.add_source_node(source_node_offset);
134 }
135 if (!destination_nodes_offset.IsNull()) {
136 channel_builder.add_destination_nodes(destination_nodes_offset);
137 }
138 if (c->has_logger()) {
139 channel_builder.add_logger(c->logger());
140 }
141 if (!logger_nodes_offset.IsNull()) {
142 channel_builder.add_logger_nodes(logger_nodes_offset);
143 }
144 if (c->has_read_method()) {
145 channel_builder.add_read_method(c->read_method());
146 }
147 if (c->has_num_readers()) {
148 channel_builder.add_num_readers(c->num_readers());
149 }
150 return channel_builder.Finish();
151}
152
Austin Schuhe309d2a2019-11-29 13:25:21 -0800153namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800154using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700155} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800156
Austin Schuhe33c08d2022-02-03 18:15:21 -0800157// Class to manage triggering events on the RT clock while replaying logs. Since
158// the RT clock can only change when we get a message, we only need to update
159// our timers when new messages are read.
160class EventNotifier {
161 public:
162 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
163 std::string_view name,
164 realtime_clock::time_point realtime_event_time)
165 : event_loop_(event_loop),
166 fn_(std::move(fn)),
167 realtime_event_time_(realtime_event_time) {
168 CHECK(event_loop_);
169 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
170
171 if (event_loop_->node() != nullptr) {
172 event_timer_->set_name(
173 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
174 } else {
175 event_timer_->set_name(name);
176 }
177 }
178
179 ~EventNotifier() { event_timer_->Disable(); }
180
James Kuszmaul09632422022-05-25 15:56:19 -0700181 // Sets the clock offset for realtime playback.
182 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
183 clock_offset_ = clock_offset;
184 }
185
Austin Schuhe33c08d2022-02-03 18:15:21 -0800186 // Returns the event trigger time.
187 realtime_clock::time_point realtime_event_time() const {
188 return realtime_event_time_;
189 }
190
191 // Observes the next message and potentially calls the callback or updates the
192 // timer.
193 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
194 realtime_clock::time_point realtime_message_time) {
195 if (realtime_message_time < realtime_event_time_) {
196 return;
197 }
198 if (called_) {
199 return;
200 }
201
202 // Move the callback wakeup time to the correct time (or make it now if
203 // there's a gap in time) now that we know it is before the next
204 // message.
205 const monotonic_clock::time_point candidate_monotonic =
206 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
207 const monotonic_clock::time_point monotonic_now =
208 event_loop_->monotonic_now();
209 if (candidate_monotonic < monotonic_now) {
210 // Whops, time went backwards. Just do it now.
211 HandleTime();
212 } else {
Philipp Schradera6712522023-07-05 20:25:11 -0700213 event_timer_->Schedule(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800214 }
215 }
216
217 private:
218 void HandleTime() {
219 if (!called_) {
220 called_ = true;
221 fn_();
222 }
223 }
224
225 EventLoop *event_loop_ = nullptr;
226 TimerHandler *event_timer_ = nullptr;
227 std::function<void()> fn_;
228
229 const realtime_clock::time_point realtime_event_time_ =
230 realtime_clock::min_time;
231
James Kuszmaul09632422022-05-25 15:56:19 -0700232 std::chrono::nanoseconds clock_offset_{0};
233
Austin Schuhe33c08d2022-02-03 18:15:21 -0800234 bool called_ = false;
235};
236
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800237LogReader::LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700238 const Configuration *replay_configuration,
239 const ReplayChannels *replay_channels)
240 : LogReader(SortParts({std::string(filename)}), replay_configuration,
241 replay_channels) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800242
Austin Schuh287d43d2020-12-04 20:19:33 -0800243LogReader::LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700244 const Configuration *replay_configuration,
245 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800246 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700247 replay_configuration_(replay_configuration),
248 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800249 SetStartTime(FLAGS_start_time);
250 SetEndTime(FLAGS_end_time);
251
Austin Schuh0ca51f32020-12-25 21:51:45 -0800252 CHECK_GT(log_files_.size(), 0u);
253 {
254 // Validate that we have the same config everwhere. This will be true if
255 // all the parts were sorted together and the configs match.
256 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800257 for (const LogFile &log_file : log_files_) {
258 if (log_file.config.get() == nullptr) {
259 LOG(FATAL) << "Couldn't find a config in " << log_file;
260 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800261 if (config == nullptr) {
262 config = log_file.config.get();
263 } else {
264 CHECK_EQ(config, log_file.config.get());
265 }
266 }
267 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800268
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700269 if (replay_channels_ != nullptr) {
270 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
271 "no messages will get replayed.";
272 }
273
Austin Schuh6331ef92020-01-07 18:28:09 -0800274 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800275
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700276 // Remap all existing remote timestamp channels. They will be recreated, and
277 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700278 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800279 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
280 "log_reader", node);
281
282 absl::btree_set<std::string_view> remote_nodes;
283
284 for (const Channel *channel : *logged_configuration()->channels()) {
285 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
286 continue;
287 }
288 if (!channel->has_destination_nodes()) {
289 continue;
290 }
291 for (const Connection *connection : *channel->destination_nodes()) {
292 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
293 node)) {
294 // Start by seeing if the split timestamp channels are being used for
295 // this message. If so, remap them.
296 const Channel *timestamp_channel = configuration::GetChannel(
297 logged_configuration(),
298 finder.SplitChannelName(channel, connection),
299 RemoteMessage::GetFullyQualifiedName(), "", node, true);
300
301 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700302 // If for some reason a timestamp channel is not NOT_LOGGED (which
303 // is unusual), then remap the channel so that the replayed channel
304 // doesn't overlap with the special separate replay we do for
305 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800306 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
307 RemapLoggedChannel<RemoteMessage>(
308 timestamp_channel->name()->string_view(), node);
309 }
310 continue;
311 }
312
313 // Otherwise collect this one up as a node to look for a combined
314 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700315 LOG(WARNING) << "Failed to find channel "
316 << finder.SplitChannelName(channel, connection)
317 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800318 remote_nodes.insert(connection->name()->string_view());
319 }
320 }
321 }
322
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700323 std::vector<const Node *> timestamp_logger_nodes =
324 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800325 for (const std::string_view remote_node : remote_nodes) {
326 const std::string channel = finder.CombinedChannelName(remote_node);
327
Austin Schuh0de30f32020-12-06 12:44:28 -0800328 // See if the log file is an old log with MessageHeader channels in it, or
329 // a newer log with RemoteMessage. If we find an older log, rename the
330 // type too along with the name.
331 if (HasChannel<MessageHeader>(channel, node)) {
332 CHECK(!HasChannel<RemoteMessage>(channel, node))
333 << ": Can't have both a MessageHeader and RemoteMessage remote "
334 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800335 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
336 // careful about updating the config, but there are fewer and fewer logs
337 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800338 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
339 "aos.message_bridge.RemoteMessage");
340 } else {
341 CHECK(HasChannel<RemoteMessage>(channel, node))
342 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
343 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
344 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800345 // Only bother to remap if there's something on the channel. We can
346 // tell if the channel was marked NOT_LOGGED or not. This makes the
347 // config not change un-necesarily when we replay a log with NOT_LOGGED
348 // messages.
349 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
350 RemapLoggedChannel<RemoteMessage>(channel, node);
351 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800352 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700353 }
354 }
355
Austin Schuh6aa77be2020-02-22 21:06:40 -0800356 if (replay_configuration) {
357 CHECK_EQ(configuration::MultiNode(configuration()),
358 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700359 << ": Log file and replay config need to both be multi or single "
360 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800361 }
362
Austin Schuh6f3babe2020-01-26 20:34:50 -0800363 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700364 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800365 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800366 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700367 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800368 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700369 << ": Log file and replay config need to have matching nodes "
370 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700371 for (const Node *node : *logged_configuration()->nodes()) {
372 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700373 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
374 << " in logged config that is not present in the replay "
375 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700376 }
377 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800378 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800379 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800380 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800381}
382
Austin Schuh6aa77be2020-02-22 21:06:40 -0800383LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700384 if (event_loop_factory_unique_ptr_) {
385 Deregister();
386 } else if (event_loop_factory_ != nullptr) {
387 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
388 "is destroyed";
389 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700390 // Zero out some buffers. It's easy to do use-after-frees on these, so make
391 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700392 if (remapped_configuration_buffer_) {
393 remapped_configuration_buffer_->Wipe();
394 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800395}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800396
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800397const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800398 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800399}
400
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800401const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800402 return remapped_configuration_;
403}
404
Austin Schuh07676622021-01-21 18:59:17 -0800405std::vector<const Node *> LogReader::LoggedNodes() const {
406 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800407}
Austin Schuh15649d62019-12-28 16:36:38 -0800408
Austin Schuh11d43732020-09-21 17:28:30 -0700409monotonic_clock::time_point LogReader::monotonic_start_time(
410 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800411 State *state =
412 states_[configuration::GetNodeIndex(configuration(), node)].get();
413 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
414
Austin Schuhf665eb42022-02-03 18:26:25 -0800415 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800416}
417
Austin Schuh11d43732020-09-21 17:28:30 -0700418realtime_clock::time_point LogReader::realtime_start_time(
419 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800420 State *state =
421 states_[configuration::GetNodeIndex(configuration(), node)].get();
422 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
423
Austin Schuhf665eb42022-02-03 18:26:25 -0800424 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800425}
426
Austin Schuh58646e22021-08-23 23:51:46 -0700427void LogReader::OnStart(std::function<void()> fn) {
428 CHECK(!configuration::MultiNode(configuration()));
429 OnStart(nullptr, std::move(fn));
430}
431
432void LogReader::OnStart(const Node *node, std::function<void()> fn) {
433 const int node_index = configuration::GetNodeIndex(configuration(), node);
434 CHECK_GE(node_index, 0);
435 CHECK_LT(node_index, static_cast<int>(states_.size()));
436 State *state = states_[node_index].get();
437 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
438
439 state->OnStart(std::move(fn));
440}
441
James Kuszmaula16a7912022-06-17 10:58:12 -0700442void LogReader::State::QueueThreadUntil(BootTimestamp time) {
443 if (threading_ == ThreadedBuffering::kYes) {
444 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
445 message_queuer_.emplace(
446 [this](const BootTimestamp queue_until) {
447 // This will be called whenever anything prompts us for any state
448 // change; there may be wakeups that result in us not having any new
449 // data to push (even if we aren't done), in which case we will return
450 // nullopt but not done().
451 if (last_queued_message_.has_value() &&
452 queue_until < last_queued_message_) {
453 return util::ThreadedQueue<TimestampedMessage,
454 BootTimestamp>::PushResult{
455 std::nullopt, false,
456 last_queued_message_ == BootTimestamp::max_time()};
457 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700458
James Kuszmaula16a7912022-06-17 10:58:12 -0700459 TimestampedMessage *message = timestamp_mapper_->Front();
460 // Upon reaching the end of the log, exit.
461 if (message == nullptr) {
462 last_queued_message_ = BootTimestamp::max_time();
463 return util::ThreadedQueue<TimestampedMessage,
464 BootTimestamp>::PushResult{std::nullopt,
465 false, true};
466 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700467
James Kuszmaula16a7912022-06-17 10:58:12 -0700468 last_queued_message_ = message->monotonic_event_time;
469 const util::ThreadedQueue<TimestampedMessage,
470 BootTimestamp>::PushResult result{
471 *message, queue_until >= last_queued_message_, false};
472 timestamp_mapper_->PopFront();
473 SeedSortedMessages();
474 return result;
475 },
476 time);
477 // Spin until the first few seconds of messages are queued up so that we
478 // don't end up with delays/inconsistent timing during the first few seconds
479 // of replay.
480 message_queuer_->WaitForNoMoreWork();
481 }
482}
483
Austin Schuh58646e22021-08-23 23:51:46 -0700484void LogReader::State::OnStart(std::function<void()> fn) {
485 on_starts_.emplace_back(std::move(fn));
486}
487
488void LogReader::State::RunOnStart() {
489 SetRealtimeOffset(monotonic_start_time(boot_count()),
490 realtime_start_time(boot_count()));
491
Alexei Strots036d84e2023-05-03 16:05:12 -0700492 VLOG(1) << "Starting for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700493 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800494 auto fn = [this]() {
495 for (size_t i = 0; i < on_starts_.size(); ++i) {
496 on_starts_[i]();
497 }
498 };
499 if (event_loop_factory_) {
500 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
501 } else {
502 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700503 }
504 stopped_ = false;
505 started_ = true;
506}
507
508void LogReader::OnEnd(std::function<void()> fn) {
509 CHECK(!configuration::MultiNode(configuration()));
510 OnEnd(nullptr, std::move(fn));
511}
512
513void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
514 const int node_index = configuration::GetNodeIndex(configuration(), node);
515 CHECK_GE(node_index, 0);
516 CHECK_LT(node_index, static_cast<int>(states_.size()));
517 State *state = states_[node_index].get();
518 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
519
520 state->OnEnd(std::move(fn));
521}
522
523void LogReader::State::OnEnd(std::function<void()> fn) {
524 on_ends_.emplace_back(std::move(fn));
525}
526
527void LogReader::State::RunOnEnd() {
Alexei Strots036d84e2023-05-03 16:05:12 -0700528 VLOG(1) << "Ending for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700529 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800530 auto fn = [this]() {
531 for (size_t i = 0; i < on_ends_.size(); ++i) {
532 on_ends_[i]();
533 }
534 };
535 if (event_loop_factory_) {
536 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
537 } else {
538 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700539 }
540
541 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800542 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700543 if (message_queuer_.has_value()) {
544 message_queuer_->StopPushing();
545 }
Austin Schuh58646e22021-08-23 23:51:46 -0700546}
547
James Kuszmaul94ca5132022-07-19 09:11:08 -0700548std::vector<
549 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
550LogReader::State::NonExclusiveChannels() {
551 CHECK_NOTNULL(node_event_loop_factory_);
552 const aos::Configuration *config = node_event_loop_factory_->configuration();
553 std::vector<
554 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
555 result{// Timing reports can be sent by logged and replayed applications.
556 {aos::configuration::GetChannel(config, "/aos",
557 "aos.timing.Report", "", node_),
558 NodeEventLoopFactory::ExclusiveSenders::kNo},
559 // AOS_LOG may be used in the log and in replay.
560 {aos::configuration::GetChannel(
561 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
562 NodeEventLoopFactory::ExclusiveSenders::kNo}};
563 for (const Node *const node : configuration::GetNodes(config)) {
564 if (node == nullptr) {
565 break;
566 }
567 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
568 config,
569 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700570 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700571 // The old-style remote timestamp channel can be populated from any
572 // channel, simulated or replayed.
573 if (old_timestamp_channel != nullptr) {
574 result.push_back(std::make_pair(
575 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
576 }
577 }
578 // Remove any channels that weren't found due to not existing in the
579 // config.
580 for (size_t ii = 0; ii < result.size();) {
581 if (result[ii].first == nullptr) {
582 result.erase(result.begin() + ii);
583 } else {
584 ++ii;
585 }
586 }
587 return result;
588}
589
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800590void LogReader::Register() {
591 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800592 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800593 Register(event_loop_factory_unique_ptr_.get());
594}
595
Austin Schuh58646e22021-08-23 23:51:46 -0700596void LogReader::RegisterWithoutStarting(
597 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800598 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700599 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800600 filters_ =
601 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800602 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700603 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800604 chrono::duration_cast<chrono::nanoseconds>(
605 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800606
Austin Schuhe639ea12021-01-25 13:00:22 -0800607 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700608 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800609 const size_t node_index =
610 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800611 std::vector<LogParts> filtered_parts = FilterPartsForNode(
612 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800613
James Kuszmaula16a7912022-06-17 10:58:12 -0700614 // We don't run with threading on the buffering for simulated event loops
615 // because we haven't attempted to validate how the interactions beteen the
616 // buffering and the timestamp mapper works when running multiple nodes
617 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800618 states_[node_index] = std::make_unique<State>(
619 filtered_parts.size() == 0u
620 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700621 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700622 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800623 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node));
Austin Schuh8bd96322020-02-13 21:18:22 -0800624 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700625 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800626 event_loop_factory_->GetNodeEventLoopFactory(node),
627 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700628
629 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800630 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800631 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800632 filters_->SetTimestampMappers(std::move(timestamp_mappers));
633
634 // Note: this needs to be set before any times are pulled, or we won't observe
635 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800636 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700637
Austin Schuh287d43d2020-12-04 20:19:33 -0800638 for (const Node *node : configuration::GetNodes(configuration())) {
639 const size_t node_index =
640 configuration::GetNodeIndex(configuration(), node);
641 State *state = states_[node_index].get();
642 for (const Node *other_node : configuration::GetNodes(configuration())) {
643 const size_t other_node_index =
644 configuration::GetNodeIndex(configuration(), other_node);
645 State *other_state = states_[other_node_index].get();
646 if (other_state != state) {
647 state->AddPeer(other_state);
648 }
649 }
650 }
651
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700652 // Register after making all the State objects so we can build references
653 // between them.
654 for (const Node *node : configuration::GetNodes(configuration())) {
655 const size_t node_index =
656 configuration::GetNodeIndex(configuration(), node);
657 State *state = states_[node_index].get();
658
Austin Schuh58646e22021-08-23 23:51:46 -0700659 // If we didn't find any log files with data in them, we won't ever get a
660 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700661 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700662 continue;
663 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700664
Austin Schuh58646e22021-08-23 23:51:46 -0700665 ++live_nodes_;
666
667 NodeEventLoopFactory *node_factory =
668 event_loop_factory_->GetNodeEventLoopFactory(node);
669 node_factory->OnStartup([this, state, node]() {
670 RegisterDuringStartup(state->MakeEventLoop(), node);
671 });
672 node_factory->OnShutdown([this, state, node]() {
673 RegisterDuringStartup(nullptr, node);
674 state->DestroyEventLoop();
675 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700676 }
677
James Kuszmaul46d82582020-05-09 19:50:09 -0700678 if (live_nodes_ == 0) {
679 LOG(FATAL)
680 << "Don't have logs from any of the nodes in the replay config--are "
681 "you sure that the replay config matches the original config?";
682 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800683
Austin Schuh87dd3832021-01-01 23:07:31 -0800684 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800685
Austin Schuh858c9f32020-08-31 16:56:12 -0700686 for (std::unique_ptr<State> &state : states_) {
687 state->SeedSortedMessages();
688 }
689
Austin Schuh6f3babe2020-01-26 20:34:50 -0800690 // Forwarding is tracked per channel. If it is enabled, we want to turn it
691 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700692 // nodes, and also replayed on the other nodes. This may not satisfy all
693 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800694 if (configuration::MultiNode(event_loop_factory_->configuration())) {
695 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
696 const Channel *channel = logged_configuration()->channels()->Get(i);
697 const Node *node = configuration::GetNode(
698 configuration(), channel->source_node()->string_view());
699
Austin Schuh8bd96322020-02-13 21:18:22 -0800700 State *state =
701 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800702
703 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700704 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800705
706 event_loop_factory_->DisableForwarding(remapped_channel);
707 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700708
709 // If we are replaying a log, we don't want a bunch of redundant messages
710 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700711 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800712 }
Austin Schuh891214d2021-11-11 20:35:02 -0800713
714 // Write pseudo start times out to file now that we are all setup.
715 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700716}
717
718void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
719 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800720 StartAfterRegister(event_loop_factory);
721}
722
723void LogReader::StartAfterRegister(
724 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700725 // We want to start the log file at the last start time of the log files
726 // from all the nodes. Compute how long each node's simulation needs to run
727 // to move time to this point.
728 distributed_clock::time_point start_time = distributed_clock::min_time;
729
730 // TODO(austin): We want an "OnStart" callback for each node rather than
731 // running until the last node.
732
733 for (std::unique_ptr<State> &state : states_) {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700734 CHECK(state);
Austin Schuh58646e22021-08-23 23:51:46 -0700735 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700736 << " for node '" << MaybeNodeName(state->node()) << "' now "
Austin Schuh58646e22021-08-23 23:51:46 -0700737 << state->monotonic_now();
738 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
739 continue;
740 }
741 // And start computing the start time on the distributed clock now that
742 // that works.
743 start_time = std::max(
744 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
745 }
746
747 // TODO(austin): If a node doesn't have a start time, we might not queue
748 // enough. If this happens, we'll explode with a frozen error eventually.
749
750 CHECK_GE(start_time, distributed_clock::epoch())
751 << ": Hmm, we have a node starting before the start of time. Offset "
752 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800753
Austin Schuhdda74ec2021-01-03 19:30:37 -0800754 {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800755 VLOG(1) << "Running until " << start_time << " in Register";
756 event_loop_factory_->RunFor(start_time.time_since_epoch());
757 VLOG(1) << "At start time";
Austin Schuhdda74ec2021-01-03 19:30:37 -0800758 }
Austin Schuh92547522019-12-28 14:33:43 -0800759
Austin Schuh8bd96322020-02-13 21:18:22 -0800760 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700761 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700762 if (state->realtime_start_time(0) != realtime_clock::min_time) {
763 state->SetRealtimeOffset(state->monotonic_start_time(0),
764 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700765 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700766 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700767 << " for node '" << MaybeNodeName(state->event_loop()->node())
768 << "' now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700769 }
770
771 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800772 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800773 }
774}
775
Austin Schuh2f8fd752020-09-01 22:38:28 -0700776message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800777 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800778 if (filters_) {
779 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800780 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800781 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800782}
783
James Kuszmaul09632422022-05-25 15:56:19 -0700784// TODO(jkuszmaul): Make in-line modifications to
785// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
786// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800787void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700788 filters_ =
789 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
790 event_loop->configuration(), logged_configuration(),
791 log_files_[0].boots, FLAGS_skip_order_validation,
792 chrono::duration_cast<chrono::nanoseconds>(
793 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
794
795 std::vector<TimestampMapper *> timestamp_mappers;
796 for (const Node *node : configuration::GetNodes(configuration())) {
797 const size_t node_index =
798 configuration::GetNodeIndex(configuration(), node);
799 std::vector<LogParts> filtered_parts = FilterPartsForNode(
800 log_files_, node != nullptr ? node->name()->string_view() : "");
801
802 states_[node_index] = std::make_unique<State>(
803 filtered_parts.size() == 0u
804 ? nullptr
805 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700806 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Naman Guptacf6d4422023-03-01 11:41:00 -0800807 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node));
James Kuszmaul09632422022-05-25 15:56:19 -0700808 State *state = states_[node_index].get();
809
810 state->SetChannelCount(logged_configuration()->channels()->size());
811 timestamp_mappers.emplace_back(state->timestamp_mapper());
812 }
813
814 filters_->SetTimestampMappers(std::move(timestamp_mappers));
815
816 for (const Node *node : configuration::GetNodes(configuration())) {
817 const size_t node_index =
818 configuration::GetNodeIndex(configuration(), node);
819 State *state = states_[node_index].get();
820 for (const Node *other_node : configuration::GetNodes(configuration())) {
821 const size_t other_node_index =
822 configuration::GetNodeIndex(configuration(), other_node);
823 State *other_state = states_[other_node_index].get();
824 if (other_state != state) {
825 state->AddPeer(other_state);
826 }
827 }
828 }
829 for (const Node *node : configuration::GetNodes(configuration())) {
830 if (node == nullptr || node->name()->string_view() ==
831 event_loop->node()->name()->string_view()) {
832 Register(event_loop, event_loop->node());
833 } else {
834 Register(nullptr, node);
835 }
836 }
Austin Schuh58646e22021-08-23 23:51:46 -0700837}
838
839void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800840 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700841 states_[configuration::GetNodeIndex(configuration(), node)].get();
842
843 // If we didn't find any log files with data in them, we won't ever get a
844 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700845 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700846 return;
847 }
James Kuszmaul09632422022-05-25 15:56:19 -0700848
849 if (event_loop != nullptr) {
850 ++live_nodes_;
851 }
Austin Schuh58646e22021-08-23 23:51:46 -0700852
853 if (event_loop_factory_ != nullptr) {
854 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
855 [this, event_loop, node]() {
856 RegisterDuringStartup(event_loop, node);
857 });
858 } else {
859 RegisterDuringStartup(event_loop, node);
860 }
861}
862
863void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700864 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700865 CHECK(event_loop->configuration() == configuration());
866 }
867
868 State *state =
869 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800870
James Kuszmaul09632422022-05-25 15:56:19 -0700871 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800872 state->ClearTimeFlags();
873 }
874
Austin Schuh858c9f32020-08-31 16:56:12 -0700875 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800876
Tyler Chatow67ddb032020-01-12 14:30:04 -0800877 // We don't run timing reports when trying to print out logged data, because
878 // otherwise we would end up printing out the timing reports themselves...
879 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700880 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700881 event_loop->SkipTimingReport();
882 event_loop->SkipAosLog();
883 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800884
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700885 for (size_t logged_channel_index = 0;
886 logged_channel_index < logged_configuration()->channels()->size();
887 ++logged_channel_index) {
888 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700889 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700890 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800891
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700892 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700893 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700894
895 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700896
Austin Schuh58646e22021-08-23 23:51:46 -0700897 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
898 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700899 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700900 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800901
Austin Schuh58646e22021-08-23 23:51:46 -0700902 // We've got a message which is being forwarded to this node.
903 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700904
905 source_state =
906 states_[configuration::GetNodeIndex(configuration(), source_node)]
907 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800908 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700909
Austin Schuh58646e22021-08-23 23:51:46 -0700910 // We are the source, and it is forwarded.
911 const bool is_forwarded =
912 configuration::ChannelIsSendableOnNode(channel, node) &&
913 configuration::ConnectionCount(channel);
914
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700915 state->SetChannel(
916 logged_channel_index,
917 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700918 event_loop && logged &&
919 configuration::ChannelIsReadableOnNode(channel, node)
920 ? event_loop->MakeRawSender(channel)
921 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700922 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700923
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700924 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700925 const Node *source_node = configuration::GetNode(
926 configuration(), channel->source_node()->string_view());
927
928 for (const Connection *connection : *channel->destination_nodes()) {
929 const bool delivery_time_is_logged =
930 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
931 source_node);
932
933 if (delivery_time_is_logged) {
934 State *destination_state =
935 states_[configuration::GetNodeIndex(
936 configuration(), connection->name()->string_view())]
937 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700938 if (destination_state) {
939 destination_state->SetRemoteTimestampSender(
940 logged_channel_index,
941 event_loop ? state->RemoteTimestampSender(channel, connection)
942 : nullptr);
943 }
Austin Schuh58646e22021-08-23 23:51:46 -0700944 }
945 }
946 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800947 }
948
Austin Schuh58646e22021-08-23 23:51:46 -0700949 if (!event_loop) {
950 state->ClearRemoteTimestampSenders();
951 state->set_timer_handler(nullptr);
952 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800953 return;
954 }
955
Austin Schuh858c9f32020-08-31 16:56:12 -0700956 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700957 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800958 --live_nodes_;
Alexei Strots036d84e2023-05-03 16:05:12 -0700959 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
960 << "' down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700961 if (exit_on_finish_ && live_nodes_ == 0 &&
962 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700963 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800964 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800965 return;
966 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700967
Austin Schuhdda74ec2021-01-03 19:30:37 -0800968 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700969
970 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
971 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800972
Austin Schuhe309d2a2019-11-29 13:25:21 -0800973 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700974 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700975 if (event_loop_factory_ != nullptr) {
976 // Only enforce exact timing in simulation.
977 if (!FLAGS_skip_order_validation) {
978 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
979 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
980 << monotonic_now << " trying to send "
981 << timestamped_message.monotonic_event_time << " failure "
982 << state->DebugString();
983 } else if (BootTimestamp{.boot = state->boot_count(),
984 .time = monotonic_now} !=
985 timestamped_message.monotonic_event_time) {
986 LOG(WARNING) << "Check failed: monotonic_now == "
987 "timestamped_message.monotonic_event_time) ("
988 << monotonic_now << " vs. "
989 << timestamped_message.monotonic_event_time
990 << "): " << FlatbufferToJson(state->event_loop()->node())
991 << " Now " << monotonic_now << " trying to send "
992 << timestamped_message.monotonic_event_time << " failure "
993 << state->DebugString();
994 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700995 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800996
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700997 if (timestamped_message.monotonic_event_time.time >
998 state->monotonic_start_time(
999 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -07001000 event_loop_factory_ != nullptr ||
1001 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001002 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001003 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001004 BootTimestamp::min_time() &&
1005 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001006 // Confirm that the message was sent on the sending node before the
1007 // destination node (this node). As a proxy, do this by making sure
1008 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001009 //
1010 // TODO(austin): <= means that the cause message (which we know) could
1011 // happen after the effect even though we know they are at the same
1012 // time. I doubt anyone will notice for a bit, but we should really
1013 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001014 BootTimestamp monotonic_remote_now =
1015 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001017 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001018 monotonic_remote_now.boot)
1019 << state->event_loop()->node()->name()->string_view() << " to "
1020 << state->remote_node(timestamped_message.channel_index)
1021 ->name()
1022 ->string_view()
1023 << " while trying to send a message on "
1024 << configuration::CleanedChannelToString(
1025 logged_configuration()->channels()->Get(
1026 timestamped_message.channel_index))
1027 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001028 CHECK_LE(timestamped_message.monotonic_remote_time,
1029 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001030 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001031 << state->remote_node(timestamped_message.channel_index)
1032 ->name()
1033 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001034 << " while trying to send a message on "
1035 << configuration::CleanedChannelToString(
1036 logged_configuration()->channels()->Get(
1037 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001038 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001039 } else if (monotonic_remote_now.boot !=
1040 timestamped_message.monotonic_remote_time.boot) {
1041 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1042 << " vs "
1043 << timestamped_message.monotonic_remote_time.boot;
1044 } else if (timestamped_message.monotonic_remote_time >
1045 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001046 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001047 << "Check failed: timestamped_message.monotonic_remote_time < "
1048 "state->monotonic_remote_now(timestamped_message.channel_"
1049 "index) ("
1050 << timestamped_message.monotonic_remote_time << " vs. "
1051 << state->monotonic_remote_now(
1052 timestamped_message.channel_index)
1053 << ") " << state->event_loop()->node()->name()->string_view()
1054 << " to "
1055 << state->remote_node(timestamped_message.channel_index)
1056 ->name()
1057 ->string_view()
1058 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001059 << " ("
1060 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001061 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001062 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001063 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001065 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001066 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001067 << ") " << state->DebugString();
1068 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001069 }
1070
Austin Schuh15649d62019-12-28 16:36:38 -08001071 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001072 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001073 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001074
Alexei Strots036d84e2023-05-03 16:05:12 -07001075 VLOG(1) << "For node '" << MaybeNodeName(state->event_loop()->node())
1076 << "' sending at " << timestamped_message.monotonic_event_time
1077 << " : " << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001078 // TODO(austin): std::move channel_data in and make that efficient in
1079 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001080 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001081 } else if (state->found_last_message() ||
1082 (!ignore_missing_data_ &&
1083 // When starting up, we can have data which was sent before
1084 // the log starts, but the timestamp was after the log
1085 // starts. This is unreasonable to avoid, so ignore the
1086 // missing data.
1087 timestamped_message.monotonic_remote_time.time >=
1088 state->monotonic_remote_start_time(
1089 timestamped_message.monotonic_remote_time.boot,
1090 timestamped_message.channel_index) &&
1091 !FLAGS_skip_missing_forwarding_entries)) {
1092 if (!state->found_last_message()) {
1093 // We've found a timestamp without data that we expect to have data
1094 // for. This likely means that we are at the end of the log file.
1095 // Record it and CHECK that in the rest of the log file, we don't find
1096 // any more data on that channel. Not all channels will end at the
1097 // same point in time since they can be in different files.
1098 VLOG(1) << "Found the last message on channel "
1099 << timestamped_message.channel_index << ", "
1100 << configuration::CleanedChannelToString(
1101 logged_configuration()->channels()->Get(
1102 timestamped_message.channel_index))
Alexei Strots036d84e2023-05-03 16:05:12 -07001103 << " on node '" << MaybeNodeName(state->event_loop()->node())
1104 << "' at " << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001105
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001106 // The user might be working with log files from 1 node but forgot to
1107 // configure the infrastructure to log data for a remote channel on
1108 // that node. That can be very hard to debug, even though the log
1109 // reader is doing the right thing. At least log a warning in that
1110 // case and tell the user what is happening so they can either update
1111 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001112 const std::vector<std::string> logger_nodes =
1113 FindLoggerNodes(log_files_);
1114 if (logger_nodes.size()) {
1115 // We have old logs which don't have the logger nodes logged. In
1116 // that case, we can't be helpful :(
1117 bool data_logged = false;
1118 const Channel *channel = logged_configuration()->channels()->Get(
1119 timestamped_message.channel_index);
1120 for (const std::string &node : logger_nodes) {
1121 data_logged |=
1122 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1123 }
1124 if (!data_logged) {
1125 LOG(WARNING) << "Got a timestamp without any logfiles which "
1126 "could contain data for channel "
1127 << configuration::CleanedChannelToString(channel);
1128 LOG(WARNING) << "Only have logs logged on ["
1129 << absl::StrJoin(logger_nodes, ", ") << "]";
1130 LOG(WARNING)
1131 << "Dropping the rest of the data on "
1132 << state->event_loop()->node()->name()->string_view();
1133 LOG(WARNING)
1134 << "Consider using --skip_missing_forwarding_entries to "
1135 "bypass this, update your config to log it, or add data "
1136 "from one of the nodes it is logged on.";
1137 }
1138 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001139 // Now that we found the end of one channel, artificially stop the
1140 // rest by setting the found_last_message bit. It is confusing when
1141 // part of your data gets replayed but not all. The rest of them will
1142 // get dropped as they are replayed to keep memory usage down.
1143 state->SetFoundLastMessage(true);
1144
1145 // Vector storing if we've seen a nullptr message or not per channel.
1146 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001147 }
1148
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001149 // Make sure that once we have seen the last message on a channel,
1150 // data doesn't start back up again. If the user wants to play
1151 // through events like this, they can set
1152 // --skip_missing_forwarding_entries or ignore_missing_data_.
1153 if (timestamped_message.data == nullptr) {
1154 state->set_last_message(timestamped_message.channel_index);
1155 } else {
1156 if (state->last_message(timestamped_message.channel_index)) {
1157 LOG(FATAL) << "Found missing data in the middle of the log file on "
1158 "channel "
1159 << timestamped_message.channel_index << " "
1160 << configuration::StrippedChannelToString(
1161 logged_configuration()->channels()->Get(
1162 timestamped_message.channel_index))
1163 << " " << timestamped_message << " "
1164 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001165 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001166 }
Austin Schuh92547522019-12-28 14:33:43 -08001167 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001168 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001169 LOG(WARNING)
1170 << "Not sending data from before the start of the log file. "
1171 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1172 .count()
1173 << " start "
1174 << monotonic_start_time(state->node()).time_since_epoch().count()
1175 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001176 }
1177
James Kuszmaula16a7912022-06-17 10:58:12 -07001178 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001179 if (next_time != BootTimestamp::max_time()) {
1180 if (next_time.boot != state->boot_count()) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001181 VLOG(1) << "Next message for node '"
Austin Schuh58646e22021-08-23 23:51:46 -07001182 << MaybeNodeName(state->event_loop()->node())
Alexei Strots036d84e2023-05-03 16:05:12 -07001183 << "' is on the next boot, " << next_time << " now is "
Austin Schuh58646e22021-08-23 23:51:46 -07001184 << state->monotonic_now();
1185 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001186 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001187 return;
1188 }
James Kuszmaul09632422022-05-25 15:56:19 -07001189 if (event_loop_factory_ != nullptr) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001190 VLOG(1) << "Scheduling for node '"
1191 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1192 << next_time.time << "("
James Kuszmaul09632422022-05-25 15:56:19 -07001193 << state->ToDistributedClock(next_time.time)
1194 << " distributed), now is " << state->monotonic_now();
1195 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001196 VLOG(1) << "Scheduling for node '"
1197 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1198 << next_time.time << ", now is " << state->monotonic_now();
James Kuszmaul09632422022-05-25 15:56:19 -07001199 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001200 // TODO(james): This can result in negative times getting passed-through
1201 // in realtime replay.
Philipp Schradera6712522023-07-05 20:25:11 -07001202 state->Schedule(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001203 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001204 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1205 << "': No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001206 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001207 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001208 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001209 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001210 // Doesn't apply to single-EventLoop replay since the watchers in question
1211 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001212 if (event_loop_factory_ != nullptr) {
Philipp Schradera6712522023-07-05 20:25:11 -07001213 state->Schedule(monotonic_now + event_loop_factory_->send_delay() +
1214 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001215 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001216 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001217
Alexei Strots036d84e2023-05-03 16:05:12 -07001218 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1219 << "': Done sending at "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001220 << state->event_loop()->context().monotonic_event_time << " now "
1221 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001222 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001223
James Kuszmaula16a7912022-06-17 10:58:12 -07001224 state->SeedSortedMessages();
1225
1226 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001227 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001228 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1229 if (start_time_ != realtime_clock::min_time) {
1230 state->SetStartTimeFlag(start_time_);
1231 }
1232 if (end_time_ != realtime_clock::max_time) {
1233 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001234 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001235 }
Austin Schuh58646e22021-08-23 23:51:46 -07001236 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001237 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001238 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001239 // Queue up messages and then set clock offsets (we don't want to set
1240 // clock offsets before we've done the work of getting the first messages
1241 // primed).
1242 state->QueueThreadUntil(
1243 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1244 std::chrono::duration<double>(
1245 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001246 state->MaybeSetClockOffset();
Philipp Schradera6712522023-07-05 20:25:11 -07001247 state->Schedule(next_time.time);
1248 state->SetUpStartupTimer();
Austin Schuh58646e22021-08-23 23:51:46 -07001249 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001250 }
1251}
1252
Austin Schuhe33c08d2022-02-03 18:15:21 -08001253void LogReader::SetEndTime(std::string end_time) {
1254 if (end_time.empty()) {
1255 SetEndTime(realtime_clock::max_time);
1256 } else {
1257 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1258 aos::realtime_clock::FromString(end_time);
1259 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1260 << "'. Expected a date in the format of "
1261 "2021-01-15_15-30-35.000000000.";
1262 SetEndTime(*parsed_end_time);
1263 }
1264}
1265
1266void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1267 end_time_ = end_time;
1268}
1269
1270void LogReader::SetStartTime(std::string start_time) {
1271 if (start_time.empty()) {
1272 SetStartTime(realtime_clock::min_time);
1273 } else {
1274 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1275 aos::realtime_clock::FromString(start_time);
1276 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1277 << "'. Expected a date in the format of "
1278 "2021-01-15_15-30-35.000000000.";
1279 SetStartTime(*parsed_start_time);
1280 }
1281}
1282
1283void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1284 start_time_ = start_time;
1285}
1286
Austin Schuhe309d2a2019-11-29 13:25:21 -08001287void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001288 // Make sure that things get destroyed in the correct order, rather than
1289 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001290 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001291 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001292 }
Austin Schuh92547522019-12-28 14:33:43 -08001293
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001294 event_loop_factory_unique_ptr_.reset();
1295 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001296}
1297
James Kuszmaul53da7f32022-09-11 11:11:55 -07001298namespace {
1299// Checks if the specified channel name/type exists in the config and, depending
1300// on the value of conflict_handling, calls conflict_handler or just dies.
1301template <typename F>
1302void CheckAndHandleRemapConflict(std::string_view new_name,
1303 std::string_view new_type,
1304 const Configuration *config,
1305 LogReader::RemapConflict conflict_handling,
1306 F conflict_handler) {
1307 const Channel *existing_channel =
1308 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1309 if (existing_channel != nullptr) {
1310 switch (conflict_handling) {
1311 case LogReader::RemapConflict::kDisallow:
1312 LOG(FATAL)
1313 << "Channel "
1314 << configuration::StrippedChannelToString(existing_channel)
1315 << " is already used--you can't remap a logged channel to it.";
1316 break;
1317 case LogReader::RemapConflict::kCascade:
1318 LOG(INFO) << "Automatically remapping "
1319 << configuration::StrippedChannelToString(existing_channel)
1320 << " to avoid conflicts.";
1321 conflict_handler();
1322 break;
1323 }
1324 }
1325}
1326} // namespace
1327
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001328void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001329 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001330 std::string_view new_type,
1331 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001332 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1333 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001334}
1335
Austin Schuh01b4c352020-09-21 23:09:39 -07001336void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1337 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001338 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001339 std::string_view new_type,
1340 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001341 if (node != nullptr) {
1342 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1343 }
1344 if (replay_channels_ != nullptr) {
1345 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1346 std::make_pair(std::string{name}, std::string{type})) !=
1347 replay_channels_->end())
1348 << "Attempted to remap channel " << name << " " << type
1349 << " which is not included in the replay channels passed to LogReader.";
1350 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001351 const Channel *remapped_channel =
1352 configuration::GetChannel(logged_configuration(), name, type, "", node);
1353 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1354 << "\", \"type\": \"" << type << "\"}";
1355 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1356 << "\"}";
1357 VLOG(1) << "Remapped "
1358 << aos::configuration::StrippedChannelToString(remapped_channel);
1359
1360 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1361 // we want it to degrade if the heuristics fail to just work.
1362 //
1363 // The easiest way to do this is going to be incredibly specific and verbose.
1364 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1365 // /original/0/spray. Then, create a map from /original/spray to
1366 // /original/0/spray for just the type we were asked for.
1367 if (name != remapped_channel->name()->string_view()) {
1368 MapT new_map;
1369 new_map.match = std::make_unique<ChannelT>();
1370 new_map.match->name = absl::StrCat(add_prefix, name);
1371 new_map.match->type = type;
1372 if (node != nullptr) {
1373 new_map.match->source_node = node->name()->str();
1374 }
1375 new_map.rename = std::make_unique<ChannelT>();
1376 new_map.rename->name =
1377 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1378 maps_.emplace_back(std::move(new_map));
1379 }
1380
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001381 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001382 const size_t channel_index =
1383 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1384 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1385 << "Already remapped channel "
1386 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001387
1388 RemappedChannel remapped_channel_struct;
1389 remapped_channel_struct.remapped_name =
1390 std::string(add_prefix) +
1391 std::string(remapped_channel->name()->string_view());
1392 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001393 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1394 CheckAndHandleRemapConflict(
1395 remapped_channel_struct.remapped_name, remapped_type,
1396 remapped_configuration_, conflict_handling,
1397 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1398 conflict_handling]() {
1399 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1400 node, add_prefix, "", conflict_handling);
1401 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001402 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001403 MakeRemappedConfig();
1404}
1405
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001406void LogReader::RenameLoggedChannel(const std::string_view name,
1407 const std::string_view type,
1408 const std::string_view new_name,
1409 const std::vector<MapT> &add_maps) {
1410 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1411}
1412
1413void LogReader::RenameLoggedChannel(const std::string_view name,
1414 const std::string_view type,
1415 const Node *const node,
1416 const std::string_view new_name,
1417 const std::vector<MapT> &add_maps) {
1418 if (node != nullptr) {
1419 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1420 }
1421 // First find the channel and rename it.
1422 const Channel *remapped_channel =
1423 configuration::GetChannel(logged_configuration(), name, type, "", node);
1424 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1425 << "\", \"type\": \"" << type << "\"}";
1426 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1427 << "\"}";
1428 VLOG(1) << "Remapped "
1429 << aos::configuration::StrippedChannelToString(remapped_channel);
1430
1431 const size_t channel_index =
1432 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1433 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1434 << "Already remapped channel "
1435 << configuration::CleanedChannelToString(remapped_channel);
1436
1437 RemappedChannel remapped_channel_struct;
1438 remapped_channel_struct.remapped_name = new_name;
1439 remapped_channel_struct.new_type.clear();
1440 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1441
1442 // Then add any provided maps.
1443 for (const MapT &map : add_maps) {
1444 maps_.push_back(map);
1445 }
1446
1447 // Finally rewrite the config.
1448 MakeRemappedConfig();
1449}
1450
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001451void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001452 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001453 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001454 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001455 << ": Can't change the mapping after the events are scheduled.";
1456 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001457 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001458
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001459 // If no remapping occurred and we are using the original config, then there
1460 // is nothing interesting to do here.
1461 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001462 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001463 return;
1464 }
1465 // Config to copy Channel definitions from. Use the specified
1466 // replay_configuration_ if it has been provided.
1467 const Configuration *const base_config = replay_configuration_ == nullptr
1468 ? logged_configuration()
1469 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001470
1471 // Create a config with all the channels, but un-sorted/merged. Collect up
1472 // the schemas while we do this. Call MergeConfiguration to sort everything,
1473 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001474
1475 // This is the builder that we use for the config containing all the new
1476 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001477 flatbuffers::FlatBufferBuilder fbb;
1478 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001479 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001480
1481 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1482 << ": Merging logic needs to be updated when the number of channel "
1483 "fields changes.";
1484
1485 // List of schemas.
1486 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1487 // Make sure our new RemoteMessage schema is in there for old logs without it.
1488 schema_map.insert(std::make_pair(
1489 RemoteMessage::GetFullyQualifiedName(),
1490 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1491 message_bridge::RemoteMessageSchema()))));
1492
1493 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001494 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001495 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001496 base_config, logged_configuration()->channels()->Get(pair.first), "",
1497 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001498 channel_offsets.emplace_back(
1499 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001500
1501 if (c->has_destination_nodes()) {
1502 for (const Connection *connection : *c->destination_nodes()) {
1503 switch (connection->timestamp_logger()) {
1504 case LoggerConfig::LOCAL_LOGGER:
1505 case LoggerConfig::NOT_LOGGED:
1506 // There is no timestamp channel associated with this, so ignore it.
1507 break;
1508
1509 case LoggerConfig::REMOTE_LOGGER:
1510 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1511 // We want to make a split timestamp channel regardless of what type
1512 // of log this used to be. No sense propagating the single
1513 // timestamp channel.
1514
1515 CHECK(connection->has_timestamp_logger_nodes());
1516 for (const flatbuffers::String *timestamp_logger_node :
1517 *connection->timestamp_logger_nodes()) {
1518 const Node *node = configuration::GetNode(
1519 logged_configuration(), timestamp_logger_node->string_view());
1520 message_bridge::ChannelTimestampFinder finder(
1521 logged_configuration(), "log_reader", node);
1522
1523 // We are assuming here that all the maps are setup correctly to
1524 // handle arbitrary timestamps. Apply the maps for this node to
1525 // see what name this ends up with.
1526 std::string name = finder.SplitChannelName(
1527 pair.second.remapped_name, c->type()->str(), connection);
1528 std::string unmapped_name = name;
1529 configuration::HandleMaps(logged_configuration()->maps(), &name,
1530 "aos.message_bridge.RemoteMessage",
1531 node);
1532 CHECK_NE(name, unmapped_name)
1533 << ": Remote timestamp channel was not remapped, this is "
1534 "very fishy";
1535 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1536 fbb.CreateString(name);
1537 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1538 fbb.CreateString("aos.message_bridge.RemoteMessage");
1539 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1540 fbb.CreateString(timestamp_logger_node->string_view());
1541
1542 // Now, build a channel. Don't log it, 2 senders, and match the
1543 // source frequency.
1544 Channel::Builder channel_builder(fbb);
1545 channel_builder.add_name(channel_name_offset);
1546 channel_builder.add_type(channel_type_offset);
1547 channel_builder.add_source_node(source_node_offset);
1548 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1549 channel_builder.add_num_senders(2);
1550 if (c->has_frequency()) {
1551 channel_builder.add_frequency(c->frequency());
1552 }
1553 channel_offsets.emplace_back(channel_builder.Finish());
1554 }
1555 break;
1556 }
1557 }
1558 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001559 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001560
Austin Schuh0de30f32020-12-06 12:44:28 -08001561 // Now reconstruct the original channels, translating types as needed
1562 for (const Channel *c : *base_config->channels()) {
1563 // Search for a mapping channel.
1564 std::string_view new_type = "";
1565 for (auto &pair : remapped_channels_) {
1566 const Channel *const remapped_channel =
1567 logged_configuration()->channels()->Get(pair.first);
1568 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1569 remapped_channel->type()->string_view() == c->type()->string_view()) {
1570 new_type = pair.second.new_type;
1571 break;
1572 }
1573 }
1574
1575 // Copy everything over.
1576 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1577
1578 // Add the schema if it doesn't exist.
1579 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1580 CHECK(c->has_schema());
1581 schema_map.insert(std::make_pair(c->type()->string_view(),
1582 RecursiveCopyFlatBuffer(c->schema())));
1583 }
1584 }
1585
1586 // The MergeConfiguration API takes a vector, not a map. Convert.
1587 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1588 while (!schema_map.empty()) {
1589 schemas.emplace_back(std::move(schema_map.begin()->second));
1590 schema_map.erase(schema_map.begin());
1591 }
1592
1593 // Create the Configuration containing the new channels that we want to add.
1594 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1595 channels_offset =
1596 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1597
1598 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001599 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001600 if (base_config->maps()) {
1601 for (const Map *map : *base_config->maps()) {
1602 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1603 }
1604 }
1605
1606 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001607 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001608 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001609 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001610 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001611 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1612 if (!map.match->type.empty()) {
1613 match_type_offset = fbb.CreateString(map.match->type);
1614 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001615 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1616 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001617 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001618 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001619 CHECK(!map.rename->name.empty());
1620 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1621 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001622 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001623 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001624 if (!match_type_offset.IsNull()) {
1625 match_builder.add_type(match_type_offset);
1626 }
1627 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001628 match_builder.add_source_node(match_source_node_offset);
1629 }
1630 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1631
Austin Schuh0de30f32020-12-06 12:44:28 -08001632 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001633 rename_builder.add_name(rename_name_offset);
1634 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1635
Austin Schuh0de30f32020-12-06 12:44:28 -08001636 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001637 map_builder.add_match(match_offset);
1638 map_builder.add_rename(rename_offset);
1639 map_offsets.emplace_back(map_builder.Finish());
1640 }
1641
Austin Schuh0de30f32020-12-06 12:44:28 -08001642 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1643 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001644
Austin Schuh0de30f32020-12-06 12:44:28 -08001645 // And copy everything else over.
1646 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1647 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1648
1649 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1650 applications_offset =
1651 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1652
1653 // Now insert everything else in unmodified.
1654 ConfigurationBuilder configuration_builder(fbb);
1655 if (!channels_offset.IsNull()) {
1656 configuration_builder.add_channels(channels_offset);
1657 }
1658 if (!maps_offsets.IsNull()) {
1659 configuration_builder.add_maps(maps_offsets);
1660 }
1661 if (!nodes_offset.IsNull()) {
1662 configuration_builder.add_nodes(nodes_offset);
1663 }
1664 if (!applications_offset.IsNull()) {
1665 configuration_builder.add_applications(applications_offset);
1666 }
1667
1668 if (base_config->has_channel_storage_duration()) {
1669 configuration_builder.add_channel_storage_duration(
1670 base_config->channel_storage_duration());
1671 }
1672
1673 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1674 << ": Merging logic needs to be updated when the number of configuration "
1675 "fields changes.";
1676
1677 fbb.Finish(configuration_builder.Finish());
1678
1679 // Clean it up and return it! By using MergeConfiguration here, we'll
1680 // actually get a deduplicated config for free too.
1681 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1682 configuration::MergeConfiguration(
1683 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1684
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001685 remapped_configuration_buffer_ =
1686 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001687 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001688
1689 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001690
1691 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001692}
1693
Naman Guptacf6d4422023-03-01 11:41:00 -08001694std::unique_ptr<const ReplayChannelIndices>
1695LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001696 if (replay_channels_ == nullptr) {
1697 return nullptr;
1698 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001699 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1700 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001701 for (auto const &channel : *replay_channels_) {
1702 const Channel *ch = configuration::GetChannel(
1703 logged_configuration(), channel.first, channel.second, "", node);
1704 if (ch == nullptr) {
1705 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1706 << " not found in configuration for node: "
1707 << node->name()->string_view() << " Skipping ...";
1708 continue;
1709 }
1710 const size_t channel_index =
1711 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001712 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001713 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001714 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1715 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001716 }
1717}
1718
Austin Schuh1c227352021-09-17 12:53:54 -07001719std::vector<const Channel *> LogReader::RemappedChannels() const {
1720 std::vector<const Channel *> result;
1721 result.reserve(remapped_channels_.size());
1722 for (auto &pair : remapped_channels_) {
1723 const Channel *const logged_channel =
1724 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1725
1726 auto channel_iterator = std::lower_bound(
1727 remapped_configuration_->channels()->cbegin(),
1728 remapped_configuration_->channels()->cend(),
1729 std::make_pair(std::string_view(pair.second.remapped_name),
1730 logged_channel->type()->string_view()),
1731 CompareChannels);
1732
1733 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1734 CHECK(EqualsChannels(
1735 *channel_iterator,
1736 std::make_pair(std::string_view(pair.second.remapped_name),
1737 logged_channel->type()->string_view())));
1738 result.push_back(*channel_iterator);
1739 }
1740 return result;
1741}
1742
Austin Schuh6f3babe2020-01-26 20:34:50 -08001743const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001744 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001745 const Channel *channel) {
1746 std::string_view channel_name = channel->name()->string_view();
1747 std::string_view channel_type = channel->type()->string_view();
1748 const int channel_index =
1749 configuration::ChannelIndex(logged_configuration(), channel);
1750 // If the channel is remapped, find the correct channel name to use.
1751 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001752 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001753 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001754 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001755 }
1756
Austin Schuhee711052020-08-24 16:06:09 -07001757 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001758 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001759 configuration(), channel_name, channel_type,
1760 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001761
1762 CHECK(remapped_channel != nullptr)
1763 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1764 << channel_type << "\"} because it is not in the provided configuration.";
1765
1766 return remapped_channel;
1767}
1768
James Kuszmaul09632422022-05-25 15:56:19 -07001769LogReader::State::State(
1770 std::unique_ptr<TimestampMapper> timestamp_mapper,
1771 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001772 std::function<void()> notice_realtime_end, const Node *node,
1773 LogReader::State::ThreadedBuffering threading,
Naman Guptacf6d4422023-03-01 11:41:00 -08001774 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices)
James Kuszmaul09632422022-05-25 15:56:19 -07001775 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001776 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001777 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001778 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001779 threading_(threading),
Naman Guptacf6d4422023-03-01 11:41:00 -08001780 replay_channel_indices_(std::move(replay_channel_indices)) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001781 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1782 // with this node. If there are no log parts for the node, there will be no
1783 // log data, and so we do not need to worry about the replay channel filters.
1784 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001785 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001786 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001787 const TimestampedMessage &message) -> bool {
1788 auto const begin = filter->cbegin();
1789 auto const end = filter->cend();
1790 // TODO: benchmark strategies for channel_index matching
1791 return std::binary_search(begin, end, message.channel_index);
1792 });
1793 }
1794}
Austin Schuh287d43d2020-12-04 20:19:33 -08001795
1796void LogReader::State::AddPeer(State *peer) {
1797 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1798 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1799 }
1800}
Austin Schuh858c9f32020-08-31 16:56:12 -07001801
Austin Schuh58646e22021-08-23 23:51:46 -07001802void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001803 NodeEventLoopFactory *node_event_loop_factory,
1804 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001805 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001806 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001807}
1808
1809void LogReader::State::SetChannelCount(size_t count) {
1810 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001811 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001812 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001813 channel_source_state_.resize(count);
1814 factory_channel_index_.resize(count);
1815 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001816}
1817
Austin Schuh58646e22021-08-23 23:51:46 -07001818void LogReader::State::SetRemoteTimestampSender(
1819 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1820 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1821}
1822
Austin Schuh858c9f32020-08-31 16:56:12 -07001823void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001824 size_t logged_channel_index, size_t factory_channel_index,
1825 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001826 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1827 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001828 channels_[logged_channel_index] = std::move(sender);
1829 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001830 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001831
Austin Schuh58646e22021-08-23 23:51:46 -07001832 if (is_forwarded) {
1833 queue_index_map_[logged_channel_index] =
1834 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001835 }
1836
1837 factory_channel_index_[logged_channel_index] = factory_channel_index;
1838}
1839
James Kuszmaula16a7912022-06-17 10:58:12 -07001840void LogReader::State::TrackMessageSendTiming(
1841 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1842 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1843 return;
1844 }
1845
1846 timing::MessageTimingT sample;
1847 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1848 sender.channel());
1849 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1850 sample.actual_send_time =
1851 sender.monotonic_sent_time().time_since_epoch().count();
1852 sample.send_time_error = aos::time::DurationInSeconds(
1853 expected_send_time - sender.monotonic_sent_time());
1854 send_timings_.push_back(sample);
1855
1856 // Somewhat arbitrarily send out timing information in batches of 100. No need
1857 // to create excessive overhead in regenerated logfiles.
1858 // TODO(james): The overhead may be fine.
1859 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1860 CHECK(timing_statistics_sender_.valid());
1861 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1862 SendMessageTimings();
1863 }
1864}
1865
1866void LogReader::State::SendMessageTimings() {
1867 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1868 return;
1869 }
1870 auto builder = timing_statistics_sender_.MakeBuilder();
1871 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1872 for (const auto &timing : send_timings_) {
1873 timing_offsets.push_back(
1874 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1875 }
1876 send_timings_.clear();
1877 flatbuffers::Offset<
1878 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1879 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1880 timing::ReplayTiming::Builder timing_builder =
1881 builder.MakeBuilder<timing::ReplayTiming>();
1882 timing_builder.add_messages(timings_offset);
1883 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1884}
1885
Austin Schuh287d43d2020-12-04 20:19:33 -08001886bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1887 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001888 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001889 uint32_t remote_queue_index = 0xffffffff;
1890
Austin Schuh287d43d2020-12-04 20:19:33 -08001891 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001892 State *source_state =
1893 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001894 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001895 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001896 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001897
Austin Schuh9942bae2021-01-07 22:06:44 -08001898 struct SentTimestamp {
1899 monotonic_clock::time_point monotonic_event_time;
1900 uint32_t queue_index;
1901 } search;
1902
Austin Schuh58646e22021-08-23 23:51:46 -07001903 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1904 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001905 search.monotonic_event_time =
1906 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001907 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001908
1909 // Find the sent time if available.
1910 auto element = std::lower_bound(
1911 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001912 [](ContiguousSentTimestamp a, SentTimestamp b) {
1913 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001914 return true;
1915 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001916 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001917 return false;
1918 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001919
1920 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001921 return true;
1922 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001923 if (a.starting_queue_index >= b.queue_index) {
1924 return false;
1925 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001926
Austin Schuh9942bae2021-01-07 22:06:44 -08001927 // If it isn't clearly below or above, it is below. Since we return
1928 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 return false;
1930 });
1931
1932 // TODO(austin): Be a bit more principled here, but we will want to do that
1933 // after the logger rewrite. We hit this when one node finishes, but the
1934 // other node isn't done yet. So there is no send time, but there is a
1935 // receive time.
1936 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001937 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1938 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001939
1940 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001941 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001942 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001943 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001944 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001945 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001946 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001947 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001948
Austin Schuh58646e22021-08-23 23:51:46 -07001949 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001950 element->actual_queue_index -
1951 element->starting_queue_index;
1952 } else {
1953 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001954 }
Austin Schuh58646e22021-08-23 23:51:46 -07001955 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1956 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001957 }
1958
James Kuszmaul09632422022-05-25 15:56:19 -07001959 if (event_loop_factory_ != nullptr &&
1960 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1961 multinode_filters_ != nullptr) {
1962 // Sanity check that we are using consistent boot uuids.
1963 State *source_state =
1964 channel_source_state_[timestamped_message.channel_index];
1965 CHECK_EQ(multinode_filters_->boot_uuid(
1966 configuration::GetNodeIndex(event_loop_->configuration(),
1967 source_state->node()),
1968 timestamped_message.monotonic_remote_time.boot),
1969 CHECK_NOTNULL(
1970 CHECK_NOTNULL(
1971 channel_source_state_[timestamped_message.channel_index])
1972 ->event_loop_)
1973 ->boot_uuid());
1974 }
1975
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001976 // Send! Use the replayed queue index here instead of the logged queue index
1977 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001978 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001979 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001980 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001981 timestamped_message.realtime_remote_time, remote_queue_index,
1982 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001983 ? CHECK_NOTNULL(multinode_filters_)
1984 ->boot_uuid(configuration::GetNodeIndex(
1985 event_loop_->configuration(),
1986 channel_source_state_[timestamped_message
1987 .channel_index]
1988 ->node()),
1989 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001990 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001991 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001992 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1993 timestamped_message.monotonic_event_time.time) {
1994 // Only track errors for non-fetched messages.
1995 TrackMessageSendTiming(
1996 *sender,
1997 timestamped_message.monotonic_event_time.time + clock_offset());
1998 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001999
Austin Schuh287d43d2020-12-04 20:19:33 -08002000 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07002001 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08002002 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
2003 // Nothing here, start a range with 0 length.
2004 ContiguousSentTimestamp timestamp;
2005 timestamp.starting_monotonic_event_time =
2006 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002007 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002008 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002009 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002010 timestamp.actual_queue_index = sender->sent_queue_index();
2011 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2012 timestamp);
2013 } else {
2014 // We've got something. See if the next timestamp is still contiguous. If
2015 // so, grow it.
2016 ContiguousSentTimestamp *back =
2017 &queue_index_map_[timestamped_message.channel_index]->back();
2018 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002019 (timestamped_message.queue_index.index -
2020 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002021 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002022 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002023 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002024 } else {
2025 // Otherwise, make a new one.
2026 ContiguousSentTimestamp timestamp;
2027 timestamp.starting_monotonic_event_time =
2028 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002029 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002030 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002031 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002032 timestamp.actual_queue_index = sender->sent_queue_index();
2033 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2034 timestamp);
2035 }
2036 }
2037
2038 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2039 // queue index diverge a couple of elements, which would be a very small
2040 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002041 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2042 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002043 // TODO(james): Currently, If running replay against a single event loop,
2044 // remote timestamps will not get replayed because this code-path only
2045 // gets triggered on the event loop that receives the forwarded message
2046 // that the timestamps correspond to. This code, as written, also doesn't
2047 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002048 State *source_state =
2049 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2050
Austin Schuh969cd602021-01-03 00:09:45 -08002051 flatbuffers::FlatBufferBuilder fbb;
2052 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002053 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2054 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002055
Austin Schuh969cd602021-01-03 00:09:45 -08002056 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002057
2058 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002059 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002060
2061 // Swap the remote and sent metrics. They are from the sender's
2062 // perspective, not the receiver's perspective.
2063 message_header_builder.add_monotonic_sent_time(
2064 sender->monotonic_sent_time().time_since_epoch().count());
2065 message_header_builder.add_realtime_sent_time(
2066 sender->realtime_sent_time().time_since_epoch().count());
2067 message_header_builder.add_queue_index(sender->sent_queue_index());
2068
Austin Schuh58646e22021-08-23 23:51:46 -07002069 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2070 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002071 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002072 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2073 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002074 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002075 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002076
2077 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002078 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002079
Austin Schuh969cd602021-01-03 00:09:45 -08002080 fbb.Finish(message_header_builder.Finish());
2081
2082 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2083 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002084 timestamped_message.monotonic_timestamp_time,
2085 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002086 }
2087
2088 return true;
2089}
2090
Austin Schuh969cd602021-01-03 00:09:45 -08002091LogReader::RemoteMessageSender::RemoteMessageSender(
2092 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2093 : event_loop_(event_loop),
2094 sender_(std::move(sender)),
2095 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2096
2097void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2098 if (remote_timestamps_.empty()) {
2099 CHECK_NOTNULL(timer_);
2100 timer_->Disable();
2101 scheduled_time_ = monotonic_clock::min_time;
2102 return;
2103 }
2104
2105 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2106 CHECK_NOTNULL(timer_);
Philipp Schradera6712522023-07-05 20:25:11 -07002107 timer_->Schedule(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002108 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002109 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2110 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002111 }
2112}
2113
2114void LogReader::RemoteMessageSender::Send(
2115 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002116 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002117 // There are 2 variants of logs.
2118 // 1) Logs without monotonic_timestamp_time
2119 // 2) Logs with monotonic_timestamp_time
2120 //
2121 // As of Jan 2021, we shouldn't have any more logs without
2122 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2123 // the effort of saving.
2124 //
2125 // This gives us 3 cases, 2 of which are undistinguishable.
2126 // 1) Old log without monotonic_timestamp_time.
2127 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2128 // remotely so we actually have monotonic_timestamp_time.
2129 // 3) New log, but the timestamp was logged on the node receiving the message
2130 // so there is no monotonic_timestamp_time.
2131 //
2132 // Our goal when replaying is to accurately reproduce the state of the world
2133 // present when logging. If a timestamp wasn't sent back across the network,
2134 // we shouldn't replay one back across the network.
2135 //
2136 // Given that we don't really care about 1, we can use the presence of the
2137 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2138 // monotonic_timestamp_time, this means the message was logged locally and
2139 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002140 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002141 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002142 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002143
Austin Schuh58646e22021-08-23 23:51:46 -07002144 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2145
Austin Schuhc41d6a82021-07-16 14:49:23 -07002146 remote_timestamps_.emplace(
2147 std::upper_bound(
2148 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002149 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002150 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2151 const Timestamp &timestamp) {
2152 return monotonic_timestamp_time <
2153 timestamp.monotonic_timestamp_time;
2154 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002155 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002156 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002157}
2158
2159void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002160 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2161 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002162 CHECK(!remote_timestamps_.empty());
2163
2164 // Send out all timestamps at the currently scheduled time.
2165 while (remote_timestamps_.front().monotonic_timestamp_time ==
2166 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002167 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2168 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002169 remote_timestamps_.pop_front();
2170 if (remote_timestamps_.empty()) {
2171 break;
2172 }
2173 }
2174 scheduled_time_ = monotonic_clock::min_time;
2175
2176 ScheduleTimestamp();
2177}
2178
2179LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002180 const Channel *channel, const Connection *connection) {
2181 message_bridge::ChannelTimestampFinder finder(event_loop_);
2182 // Look at any pre-created channel/connection pairs.
2183 {
2184 auto it =
2185 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2186 if (it != channel_timestamp_loggers_.end()) {
2187 return it->second.get();
2188 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002189 }
2190
Austin Schuh61e973f2021-02-21 21:43:56 -08002191 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2192 // to.
2193 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2194
2195 {
2196 // See if that has been created before. If so, cache it in
2197 // channel_timestamp_loggers_ and return.
2198 auto it = timestamp_loggers_.find(timestamp_channel);
2199 if (it != timestamp_loggers_.end()) {
2200 CHECK(channel_timestamp_loggers_
2201 .try_emplace(std::make_pair(channel, connection), it->second)
2202 .second);
2203 return it->second.get();
2204 }
2205 }
2206
2207 // Otherwise, make a sender, save it, and cache it.
2208 auto result = channel_timestamp_loggers_.try_emplace(
2209 std::make_pair(channel, connection),
2210 std::make_shared<RemoteMessageSender>(
2211 event_loop()->MakeSender<RemoteMessage>(
2212 timestamp_channel->name()->string_view()),
2213 event_loop()));
2214
2215 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2216 .second);
2217 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002218}
2219
Austin Schuhdda74ec2021-01-03 19:30:37 -08002220TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002221 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002222 if (message_queuer_.has_value()) {
2223 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2224 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2225 message_queuer_->SetState(
2226 message.value().monotonic_event_time +
2227 std::chrono::duration_cast<std::chrono::nanoseconds>(
2228 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2229 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002230 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002231 CHECK(timestamp_mapper_ != nullptr);
2232 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2233 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002234
James Kuszmaula16a7912022-06-17 10:58:12 -07002235 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002236
Alexei Strots036d84e2023-05-03 16:05:12 -07002237 VLOG(2) << "Node '" << MaybeNodeName(event_loop_->node())
2238 << "': PopOldest Popping " << result.monotonic_event_time;
James Kuszmaula16a7912022-06-17 10:58:12 -07002239 timestamp_mapper_->PopFront();
2240 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002241
James Kuszmaula16a7912022-06-17 10:58:12 -07002242 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002243
James Kuszmaula16a7912022-06-17 10:58:12 -07002244 VLOG(1) << "Popped " << result
2245 << configuration::CleanedChannelToString(
2246 event_loop_->configuration()->channels()->Get(
2247 factory_channel_index_[result.channel_index]));
2248 return result;
2249 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002250}
2251
James Kuszmaula16a7912022-06-17 10:58:12 -07002252BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2253 if (!message_queuer_.has_value()) {
2254 return SingleThreadedOldestMessageTime();
2255 }
2256 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2257 if (!message.has_value()) {
2258 return BootTimestamp::max_time();
2259 }
2260 if (message.value().monotonic_event_time.boot == boot_count()) {
2261 ObserveNextMessage(message.value().monotonic_event_time.time,
2262 message.value().realtime_event_time);
2263 }
2264 return message.value().monotonic_event_time;
2265}
2266
2267BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2268 CHECK(!message_queuer_.has_value())
2269 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2270 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002271 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002272 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002273 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002274 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2275 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002276 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002277 }
Alexei Strots036d84e2023-05-03 16:05:12 -07002278 VLOG(2) << "Node '" << MaybeNodeName(node()) << "': oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002279 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002280 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2281 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2282 result_ptr->realtime_event_time);
2283 }
Austin Schuh58646e22021-08-23 23:51:46 -07002284 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002285}
2286
2287void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002288 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002289
Austin Schuhe639ea12021-01-25 13:00:22 -08002290 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2291 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002292}
2293
2294void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002295 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002296 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002297 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002298 for (size_t i = 0; i < channels_.size(); ++i) {
2299 channels_[i].reset();
2300 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002301 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002302 channel_timestamp_loggers_.clear();
2303 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002304 event_loop_unique_ptr_.reset();
2305 event_loop_ = nullptr;
2306 timer_handler_ = nullptr;
2307 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002308 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002309}
2310
Austin Schuhe33c08d2022-02-03 18:15:21 -08002311void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2312 if (start_time != realtime_clock::min_time) {
2313 start_event_notifier_ = std::make_unique<EventNotifier>(
2314 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2315 }
2316}
2317
2318void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2319 if (end_time != realtime_clock::max_time) {
2320 end_event_notifier_ = std::make_unique<EventNotifier>(
2321 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2322 }
2323}
2324
2325void LogReader::State::ObserveNextMessage(
2326 monotonic_clock::time_point monotonic_event,
2327 realtime_clock::time_point realtime_event) {
2328 if (start_event_notifier_) {
2329 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2330 }
2331 if (end_event_notifier_) {
2332 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2333 }
2334}
2335
2336void LogReader::State::ClearTimeFlags() {
2337 start_event_notifier_.reset();
2338 end_event_notifier_.reset();
2339}
2340
2341void LogReader::State::NotifyLogfileStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002342 // If the start_event_notifier_ is set, that means that a realtime start time
2343 // was set manually; when the override is set, we want to delay any startup
2344 // handlers that would've happened before requested start time until that
2345 // start time.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002346 if (start_event_notifier_) {
Philipp Schrader790cb542023-07-05 21:06:52 -07002347 // Only call OnStart() if the start time for this node
2348 // (realtime_start_time())
Austin Schuhe33c08d2022-02-03 18:15:21 -08002349 if (start_event_notifier_->realtime_event_time() >
2350 realtime_start_time(boot_count())) {
2351 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2352 << " > " << realtime_start_time(boot_count());
2353 return;
2354 }
2355 }
2356 if (found_last_message_) {
2357 VLOG(1) << "Last message already found, bailing";
2358 return;
2359 }
2360 RunOnStart();
2361}
2362
2363void LogReader::State::NotifyFlagStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002364 // Should only be called if start_event_notifier_ has been set (which happens
2365 // as part of setting an explicit start time); only call the startup functions
2366 // that occurred *before* the start flag value.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002367 if (start_event_notifier_->realtime_event_time() >=
2368 realtime_start_time(boot_count())) {
2369 RunOnStart();
2370 }
2371}
2372
2373void LogReader::State::NotifyLogfileEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002374 // Don't execute the OnEnd handlers if the logfile was ended artifically
2375 // early.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002376 if (found_last_message_) {
2377 return;
2378 }
2379
James Kuszmaul82c3b512023-07-08 20:25:41 -07002380 // Ensure that we only call OnEnd() if OnStart() was already called for this
2381 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002382 if (!stopped_ && started_) {
2383 RunOnEnd();
2384 }
2385}
2386
2387void LogReader::State::NotifyFlagEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002388 // Ensure that we only call OnEnd() if OnStart() was already called for this
2389 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002390 if (!stopped_ && started_) {
2391 RunOnEnd();
2392 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002393 CHECK(notice_realtime_end_);
2394 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002395 }
2396}
2397
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002398void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002399 if (node_event_loop_factory_ == nullptr) {
2400 // If not running with simulated event loop, set the monotonic clock
2401 // offset.
2402 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2403
2404 if (start_event_notifier_) {
2405 start_event_notifier_->SetClockOffset(clock_offset_);
2406 }
2407 if (end_event_notifier_) {
2408 end_event_notifier_->SetClockOffset(clock_offset_);
2409 }
2410 }
2411}
2412
James Kuszmaulb67409b2022-06-20 16:25:03 -07002413void LogReader::SetRealtimeReplayRate(double replay_rate) {
2414 CHECK(event_loop_factory_ != nullptr)
2415 << ": Can't set replay rate without an event loop factory (have you "
2416 "called Register()?).";
2417 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2418}
2419
James Kuszmaulb11a1502022-07-01 16:02:25 -07002420void LogReader::NoticeRealtimeEnd() {
2421 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2422 --live_nodes_with_realtime_time_end_;
2423 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2424 event_loop_factory_ != nullptr) {
2425 event_loop_factory_->Exit();
2426 }
2427}
2428
Austin Schuhe309d2a2019-11-29 13:25:21 -08002429} // namespace logger
2430} // namespace aos