blob: d0957bfe5e860045e2e008cec59d1ba893b3a681 [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>
Eric Schmiedebergae00e732023-04-12 15:53:17 -060010#include <utility>
Austin Schuhe309d2a2019-11-29 13:25:21 -080011#include <vector>
12
Austin Schuh2f8fd752020-09-01 22:38:28 -070013#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080014#include "absl/types/span.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070015#include "flatbuffers/flatbuffers.h"
16#include "openssl/sha.h"
17
Austin Schuhe309d2a2019-11-29 13:25:21 -080018#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070019#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070020#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080021#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070023#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080024#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080025#include "aos/network/remote_message_generated.h"
26#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080027#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080028#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080029#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070030#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070031#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080032
Austin Schuh15649d62019-12-28 16:36:38 -080033DEFINE_bool(skip_missing_forwarding_entries, false,
34 "If true, drop any forwarding entries with missing data. If "
35 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080036
Austin Schuh0ca1fd32020-12-18 22:53:05 -080037DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080038
Austin Schuh2f8fd752020-09-01 22:38:28 -070039DEFINE_bool(skip_order_validation, false,
40 "If true, ignore any out of orderness in replay");
41
Austin Schuhf0688662020-12-19 15:37:45 -080042DEFINE_double(
43 time_estimation_buffer_seconds, 2.0,
44 "The time to buffer ahead in the log file to accurately reconstruct time.");
45
Austin Schuhe33c08d2022-02-03 18:15:21 -080046DEFINE_string(
47 start_time, "",
48 "If set, start at this point in time in the log on the realtime clock.");
49DEFINE_string(
50 end_time, "",
51 "If set, end at this point in time in the log on the realtime clock.");
52
James Kuszmaul09632422022-05-25 15:56:19 -070053DEFINE_bool(drop_realtime_messages_before_start, false,
54 "If set, will drop any messages sent before the start of the "
55 "logfile in realtime replay. Setting this guarantees consistency "
56 "in timing with the original logfile, but means that you lose "
57 "access to fetched low-frequency messages.");
58
James Kuszmaula16a7912022-06-17 10:58:12 -070059DEFINE_double(
60 threaded_look_ahead_seconds, 2.0,
61 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
62 "Can validly be zero, but higher values are encouraged for realtime replay "
63 "in order to prevent the replay from ever having to block on waiting for "
64 "the reader to find the next message.");
65
Austin Schuhe309d2a2019-11-29 13:25:21 -080066namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070067namespace configuration {
68// We don't really want to expose this publicly, but log reader doesn't really
69// want to re-implement it.
70void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
71 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070072} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080073namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070074namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080075
Austin Schuh1c227352021-09-17 12:53:54 -070076bool CompareChannels(const Channel *c,
77 ::std::pair<std::string_view, std::string_view> p) {
78 int name_compare = c->name()->string_view().compare(p.first);
79 if (name_compare == 0) {
80 return c->type()->string_view() < p.second;
81 } else if (name_compare < 0) {
82 return true;
83 } else {
84 return false;
85 }
86}
87
88bool EqualsChannels(const Channel *c,
89 ::std::pair<std::string_view, std::string_view> p) {
90 return c->name()->string_view() == p.first &&
91 c->type()->string_view() == p.second;
92}
93
Austin Schuh0de30f32020-12-06 12:44:28 -080094// Copies the channel, removing the schema as we go. If new_name is provided,
95// it is used instead of the name inside the channel. If new_type is provided,
96// it is used instead of the type in the channel.
97flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
98 std::string_view new_name,
99 std::string_view new_type,
100 flatbuffers::FlatBufferBuilder *fbb) {
101 flatbuffers::Offset<flatbuffers::String> name_offset =
102 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
103 : new_name);
104 flatbuffers::Offset<flatbuffers::String> type_offset =
105 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
106 flatbuffers::Offset<flatbuffers::String> source_node_offset =
107 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
108 : 0;
109
110 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
111 destination_nodes_offset =
112 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
113
114 flatbuffers::Offset<
115 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
116 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
117
118 Channel::Builder channel_builder(*fbb);
119 channel_builder.add_name(name_offset);
120 channel_builder.add_type(type_offset);
121 if (c->has_frequency()) {
122 channel_builder.add_frequency(c->frequency());
123 }
124 if (c->has_max_size()) {
125 channel_builder.add_max_size(c->max_size());
126 }
127 if (c->has_num_senders()) {
128 channel_builder.add_num_senders(c->num_senders());
129 }
130 if (c->has_num_watchers()) {
131 channel_builder.add_num_watchers(c->num_watchers());
132 }
133 if (!source_node_offset.IsNull()) {
134 channel_builder.add_source_node(source_node_offset);
135 }
136 if (!destination_nodes_offset.IsNull()) {
137 channel_builder.add_destination_nodes(destination_nodes_offset);
138 }
139 if (c->has_logger()) {
140 channel_builder.add_logger(c->logger());
141 }
142 if (!logger_nodes_offset.IsNull()) {
143 channel_builder.add_logger_nodes(logger_nodes_offset);
144 }
145 if (c->has_read_method()) {
146 channel_builder.add_read_method(c->read_method());
147 }
148 if (c->has_num_readers()) {
149 channel_builder.add_num_readers(c->num_readers());
150 }
151 return channel_builder.Finish();
152}
153
Austin Schuhe309d2a2019-11-29 13:25:21 -0800154namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800155using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700156} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800157
Austin Schuhe33c08d2022-02-03 18:15:21 -0800158// Class to manage triggering events on the RT clock while replaying logs. Since
159// the RT clock can only change when we get a message, we only need to update
160// our timers when new messages are read.
161class EventNotifier {
162 public:
163 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
164 std::string_view name,
165 realtime_clock::time_point realtime_event_time)
166 : event_loop_(event_loop),
167 fn_(std::move(fn)),
168 realtime_event_time_(realtime_event_time) {
169 CHECK(event_loop_);
170 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
171
172 if (event_loop_->node() != nullptr) {
173 event_timer_->set_name(
174 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
175 } else {
176 event_timer_->set_name(name);
177 }
178 }
179
180 ~EventNotifier() { event_timer_->Disable(); }
181
James Kuszmaul09632422022-05-25 15:56:19 -0700182 // Sets the clock offset for realtime playback.
183 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
184 clock_offset_ = clock_offset;
185 }
186
Austin Schuhe33c08d2022-02-03 18:15:21 -0800187 // Returns the event trigger time.
188 realtime_clock::time_point realtime_event_time() const {
189 return realtime_event_time_;
190 }
191
192 // Observes the next message and potentially calls the callback or updates the
193 // timer.
194 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
195 realtime_clock::time_point realtime_message_time) {
196 if (realtime_message_time < realtime_event_time_) {
197 return;
198 }
199 if (called_) {
200 return;
201 }
202
203 // Move the callback wakeup time to the correct time (or make it now if
204 // there's a gap in time) now that we know it is before the next
205 // message.
206 const monotonic_clock::time_point candidate_monotonic =
207 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
208 const monotonic_clock::time_point monotonic_now =
209 event_loop_->monotonic_now();
210 if (candidate_monotonic < monotonic_now) {
211 // Whops, time went backwards. Just do it now.
212 HandleTime();
213 } else {
Philipp Schradera6712522023-07-05 20:25:11 -0700214 event_timer_->Schedule(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800215 }
216 }
217
218 private:
219 void HandleTime() {
220 if (!called_) {
221 called_ = true;
222 fn_();
223 }
224 }
225
226 EventLoop *event_loop_ = nullptr;
227 TimerHandler *event_timer_ = nullptr;
228 std::function<void()> fn_;
229
230 const realtime_clock::time_point realtime_event_time_ =
231 realtime_clock::min_time;
232
James Kuszmaul09632422022-05-25 15:56:19 -0700233 std::chrono::nanoseconds clock_offset_{0};
234
Austin Schuhe33c08d2022-02-03 18:15:21 -0800235 bool called_ = false;
236};
237
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800238LogReader::LogReader(std::string_view filename,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700239 const Configuration *replay_configuration,
240 const ReplayChannels *replay_channels)
241 : LogReader(SortParts({std::string(filename)}), replay_configuration,
242 replay_channels) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800243
Austin Schuh287d43d2020-12-04 20:19:33 -0800244LogReader::LogReader(std::vector<LogFile> log_files,
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700245 const Configuration *replay_configuration,
246 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800247 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700248 replay_configuration_(replay_configuration),
249 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800250 SetStartTime(FLAGS_start_time);
251 SetEndTime(FLAGS_end_time);
252
Austin Schuh0ca51f32020-12-25 21:51:45 -0800253 CHECK_GT(log_files_.size(), 0u);
254 {
255 // Validate that we have the same config everwhere. This will be true if
256 // all the parts were sorted together and the configs match.
257 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800258 for (const LogFile &log_file : log_files_) {
259 if (log_file.config.get() == nullptr) {
260 LOG(FATAL) << "Couldn't find a config in " << log_file;
261 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800262 if (config == nullptr) {
263 config = log_file.config.get();
264 } else {
265 CHECK_EQ(config, log_file.config.get());
266 }
267 }
268 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800269
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700270 if (replay_channels_ != nullptr) {
271 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
272 "no messages will get replayed.";
273 }
274
Austin Schuh6331ef92020-01-07 18:28:09 -0800275 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800276
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700277 // Remap all existing remote timestamp channels. They will be recreated, and
278 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700279 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800280 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
281 "log_reader", node);
282
283 absl::btree_set<std::string_view> remote_nodes;
284
285 for (const Channel *channel : *logged_configuration()->channels()) {
286 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
287 continue;
288 }
289 if (!channel->has_destination_nodes()) {
290 continue;
291 }
292 for (const Connection *connection : *channel->destination_nodes()) {
293 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
294 node)) {
295 // Start by seeing if the split timestamp channels are being used for
296 // this message. If so, remap them.
297 const Channel *timestamp_channel = configuration::GetChannel(
298 logged_configuration(),
299 finder.SplitChannelName(channel, connection),
300 RemoteMessage::GetFullyQualifiedName(), "", node, true);
301
302 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700303 // If for some reason a timestamp channel is not NOT_LOGGED (which
304 // is unusual), then remap the channel so that the replayed channel
305 // doesn't overlap with the special separate replay we do for
306 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800307 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
308 RemapLoggedChannel<RemoteMessage>(
309 timestamp_channel->name()->string_view(), node);
310 }
311 continue;
312 }
313
314 // Otherwise collect this one up as a node to look for a combined
315 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700316 LOG(WARNING) << "Failed to find channel "
317 << finder.SplitChannelName(channel, connection)
318 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800319 remote_nodes.insert(connection->name()->string_view());
320 }
321 }
322 }
323
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700324 std::vector<const Node *> timestamp_logger_nodes =
325 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800326 for (const std::string_view remote_node : remote_nodes) {
327 const std::string channel = finder.CombinedChannelName(remote_node);
328
Austin Schuh0de30f32020-12-06 12:44:28 -0800329 // See if the log file is an old log with MessageHeader channels in it, or
330 // a newer log with RemoteMessage. If we find an older log, rename the
331 // type too along with the name.
332 if (HasChannel<MessageHeader>(channel, node)) {
333 CHECK(!HasChannel<RemoteMessage>(channel, node))
334 << ": Can't have both a MessageHeader and RemoteMessage remote "
335 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800336 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
337 // careful about updating the config, but there are fewer and fewer logs
338 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800339 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
340 "aos.message_bridge.RemoteMessage");
341 } else {
342 CHECK(HasChannel<RemoteMessage>(channel, node))
343 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
344 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
345 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800346 // Only bother to remap if there's something on the channel. We can
347 // tell if the channel was marked NOT_LOGGED or not. This makes the
348 // config not change un-necesarily when we replay a log with NOT_LOGGED
349 // messages.
350 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
351 RemapLoggedChannel<RemoteMessage>(channel, node);
352 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800353 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700354 }
355 }
356
Austin Schuh6aa77be2020-02-22 21:06:40 -0800357 if (replay_configuration) {
358 CHECK_EQ(configuration::MultiNode(configuration()),
359 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700360 << ": Log file and replay config need to both be multi or single "
361 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800362 }
363
Austin Schuh6f3babe2020-01-26 20:34:50 -0800364 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700365 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800366 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800367 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700368 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800369 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700370 << ": Log file and replay config need to have matching nodes "
371 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700372 for (const Node *node : *logged_configuration()->nodes()) {
373 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700374 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
375 << " in logged config that is not present in the replay "
376 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700377 }
378 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800379 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800380 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800381 }
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600382
383 before_send_callbacks_.resize(configuration()->channels()->size());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800384}
385
Austin Schuh6aa77be2020-02-22 21:06:40 -0800386LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700387 if (event_loop_factory_unique_ptr_) {
388 Deregister();
389 } else if (event_loop_factory_ != nullptr) {
390 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
391 "is destroyed";
392 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700393 // Zero out some buffers. It's easy to do use-after-frees on these, so make
394 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700395 if (remapped_configuration_buffer_) {
396 remapped_configuration_buffer_->Wipe();
397 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800398}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800399
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800400const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800401 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800402}
403
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800404const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800405 return remapped_configuration_;
406}
407
Austin Schuh07676622021-01-21 18:59:17 -0800408std::vector<const Node *> LogReader::LoggedNodes() const {
409 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800410}
Austin Schuh15649d62019-12-28 16:36:38 -0800411
Austin Schuh11d43732020-09-21 17:28:30 -0700412monotonic_clock::time_point LogReader::monotonic_start_time(
413 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800414 State *state =
415 states_[configuration::GetNodeIndex(configuration(), node)].get();
416 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
417
Austin Schuhf665eb42022-02-03 18:26:25 -0800418 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800419}
420
Austin Schuh11d43732020-09-21 17:28:30 -0700421realtime_clock::time_point LogReader::realtime_start_time(
422 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800423 State *state =
424 states_[configuration::GetNodeIndex(configuration(), node)].get();
425 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
426
Austin Schuhf665eb42022-02-03 18:26:25 -0800427 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800428}
429
Austin Schuh58646e22021-08-23 23:51:46 -0700430void LogReader::OnStart(std::function<void()> fn) {
431 CHECK(!configuration::MultiNode(configuration()));
432 OnStart(nullptr, std::move(fn));
433}
434
435void LogReader::OnStart(const Node *node, std::function<void()> fn) {
436 const int node_index = configuration::GetNodeIndex(configuration(), node);
437 CHECK_GE(node_index, 0);
438 CHECK_LT(node_index, static_cast<int>(states_.size()));
439 State *state = states_[node_index].get();
440 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
441
442 state->OnStart(std::move(fn));
443}
444
James Kuszmaula16a7912022-06-17 10:58:12 -0700445void LogReader::State::QueueThreadUntil(BootTimestamp time) {
446 if (threading_ == ThreadedBuffering::kYes) {
447 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
448 message_queuer_.emplace(
449 [this](const BootTimestamp queue_until) {
450 // This will be called whenever anything prompts us for any state
451 // change; there may be wakeups that result in us not having any new
452 // data to push (even if we aren't done), in which case we will return
453 // nullopt but not done().
454 if (last_queued_message_.has_value() &&
455 queue_until < last_queued_message_) {
456 return util::ThreadedQueue<TimestampedMessage,
457 BootTimestamp>::PushResult{
458 std::nullopt, false,
459 last_queued_message_ == BootTimestamp::max_time()};
460 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700461
James Kuszmaula16a7912022-06-17 10:58:12 -0700462 TimestampedMessage *message = timestamp_mapper_->Front();
463 // Upon reaching the end of the log, exit.
464 if (message == nullptr) {
465 last_queued_message_ = BootTimestamp::max_time();
466 return util::ThreadedQueue<TimestampedMessage,
467 BootTimestamp>::PushResult{std::nullopt,
468 false, true};
469 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700470
James Kuszmaula16a7912022-06-17 10:58:12 -0700471 last_queued_message_ = message->monotonic_event_time;
472 const util::ThreadedQueue<TimestampedMessage,
473 BootTimestamp>::PushResult result{
474 *message, queue_until >= last_queued_message_, false};
475 timestamp_mapper_->PopFront();
476 SeedSortedMessages();
477 return result;
478 },
479 time);
480 // Spin until the first few seconds of messages are queued up so that we
481 // don't end up with delays/inconsistent timing during the first few seconds
482 // of replay.
483 message_queuer_->WaitForNoMoreWork();
484 }
485}
486
Austin Schuh58646e22021-08-23 23:51:46 -0700487void LogReader::State::OnStart(std::function<void()> fn) {
488 on_starts_.emplace_back(std::move(fn));
489}
490
491void LogReader::State::RunOnStart() {
492 SetRealtimeOffset(monotonic_start_time(boot_count()),
493 realtime_start_time(boot_count()));
494
Alexei Strots036d84e2023-05-03 16:05:12 -0700495 VLOG(1) << "Starting for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700496 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800497 auto fn = [this]() {
498 for (size_t i = 0; i < on_starts_.size(); ++i) {
499 on_starts_[i]();
500 }
501 };
502 if (event_loop_factory_) {
503 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
504 } else {
505 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700506 }
507 stopped_ = false;
508 started_ = true;
509}
510
511void LogReader::OnEnd(std::function<void()> fn) {
512 CHECK(!configuration::MultiNode(configuration()));
513 OnEnd(nullptr, std::move(fn));
514}
515
516void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
517 const int node_index = configuration::GetNodeIndex(configuration(), node);
518 CHECK_GE(node_index, 0);
519 CHECK_LT(node_index, static_cast<int>(states_.size()));
520 State *state = states_[node_index].get();
521 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
522
523 state->OnEnd(std::move(fn));
524}
525
526void LogReader::State::OnEnd(std::function<void()> fn) {
527 on_ends_.emplace_back(std::move(fn));
528}
529
530void LogReader::State::RunOnEnd() {
Alexei Strots036d84e2023-05-03 16:05:12 -0700531 VLOG(1) << "Ending for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700532 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800533 auto fn = [this]() {
534 for (size_t i = 0; i < on_ends_.size(); ++i) {
535 on_ends_[i]();
536 }
537 };
538 if (event_loop_factory_) {
539 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
540 } else {
541 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700542 }
543
544 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800545 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700546 if (message_queuer_.has_value()) {
547 message_queuer_->StopPushing();
548 }
Austin Schuh58646e22021-08-23 23:51:46 -0700549}
550
James Kuszmaul94ca5132022-07-19 09:11:08 -0700551std::vector<
552 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
553LogReader::State::NonExclusiveChannels() {
554 CHECK_NOTNULL(node_event_loop_factory_);
555 const aos::Configuration *config = node_event_loop_factory_->configuration();
556 std::vector<
557 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
558 result{// Timing reports can be sent by logged and replayed applications.
559 {aos::configuration::GetChannel(config, "/aos",
560 "aos.timing.Report", "", node_),
561 NodeEventLoopFactory::ExclusiveSenders::kNo},
562 // AOS_LOG may be used in the log and in replay.
563 {aos::configuration::GetChannel(
564 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
565 NodeEventLoopFactory::ExclusiveSenders::kNo}};
566 for (const Node *const node : configuration::GetNodes(config)) {
567 if (node == nullptr) {
568 break;
569 }
570 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
571 config,
572 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700573 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700574 // The old-style remote timestamp channel can be populated from any
575 // channel, simulated or replayed.
576 if (old_timestamp_channel != nullptr) {
577 result.push_back(std::make_pair(
578 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
579 }
580 }
581 // Remove any channels that weren't found due to not existing in the
582 // config.
583 for (size_t ii = 0; ii < result.size();) {
584 if (result[ii].first == nullptr) {
585 result.erase(result.begin() + ii);
586 } else {
587 ++ii;
588 }
589 }
590 return result;
591}
592
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800593void LogReader::Register() {
594 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800595 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800596 Register(event_loop_factory_unique_ptr_.get());
597}
598
Austin Schuh58646e22021-08-23 23:51:46 -0700599void LogReader::RegisterWithoutStarting(
600 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800601 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700602 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800603 filters_ =
604 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800605 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700606 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800607 chrono::duration_cast<chrono::nanoseconds>(
608 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800609
Austin Schuhe639ea12021-01-25 13:00:22 -0800610 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700611 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800612 const size_t node_index =
613 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800614 std::vector<LogParts> filtered_parts = FilterPartsForNode(
615 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800616
James Kuszmaula16a7912022-06-17 10:58:12 -0700617 // We don't run with threading on the buffering for simulated event loops
618 // because we haven't attempted to validate how the interactions beteen the
619 // buffering and the timestamp mapper works when running multiple nodes
620 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800621 states_[node_index] = std::make_unique<State>(
622 filtered_parts.size() == 0u
623 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700624 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700625 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600626 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node),
627 before_send_callbacks_);
Austin Schuh8bd96322020-02-13 21:18:22 -0800628 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700629 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800630 event_loop_factory_->GetNodeEventLoopFactory(node),
631 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700632
633 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800634 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800635 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800636 filters_->SetTimestampMappers(std::move(timestamp_mappers));
637
638 // Note: this needs to be set before any times are pulled, or we won't observe
639 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800640 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700641
Austin Schuh287d43d2020-12-04 20:19:33 -0800642 for (const Node *node : configuration::GetNodes(configuration())) {
643 const size_t node_index =
644 configuration::GetNodeIndex(configuration(), node);
645 State *state = states_[node_index].get();
646 for (const Node *other_node : configuration::GetNodes(configuration())) {
647 const size_t other_node_index =
648 configuration::GetNodeIndex(configuration(), other_node);
649 State *other_state = states_[other_node_index].get();
650 if (other_state != state) {
651 state->AddPeer(other_state);
652 }
653 }
654 }
655
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700656 // Register after making all the State objects so we can build references
657 // between them.
658 for (const Node *node : configuration::GetNodes(configuration())) {
659 const size_t node_index =
660 configuration::GetNodeIndex(configuration(), node);
661 State *state = states_[node_index].get();
662
Austin Schuh58646e22021-08-23 23:51:46 -0700663 // If we didn't find any log files with data in them, we won't ever get a
664 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700665 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700666 continue;
667 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700668
Austin Schuh58646e22021-08-23 23:51:46 -0700669 ++live_nodes_;
670
671 NodeEventLoopFactory *node_factory =
672 event_loop_factory_->GetNodeEventLoopFactory(node);
673 node_factory->OnStartup([this, state, node]() {
674 RegisterDuringStartup(state->MakeEventLoop(), node);
675 });
676 node_factory->OnShutdown([this, state, node]() {
677 RegisterDuringStartup(nullptr, node);
678 state->DestroyEventLoop();
679 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700680 }
681
James Kuszmaul46d82582020-05-09 19:50:09 -0700682 if (live_nodes_ == 0) {
683 LOG(FATAL)
684 << "Don't have logs from any of the nodes in the replay config--are "
685 "you sure that the replay config matches the original config?";
686 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800687
Austin Schuh87dd3832021-01-01 23:07:31 -0800688 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800689
Austin Schuh858c9f32020-08-31 16:56:12 -0700690 for (std::unique_ptr<State> &state : states_) {
691 state->SeedSortedMessages();
692 }
693
Austin Schuh6f3babe2020-01-26 20:34:50 -0800694 // Forwarding is tracked per channel. If it is enabled, we want to turn it
695 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700696 // nodes, and also replayed on the other nodes. This may not satisfy all
697 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800698 if (configuration::MultiNode(event_loop_factory_->configuration())) {
699 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
700 const Channel *channel = logged_configuration()->channels()->Get(i);
701 const Node *node = configuration::GetNode(
702 configuration(), channel->source_node()->string_view());
703
Austin Schuh8bd96322020-02-13 21:18:22 -0800704 State *state =
705 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800706
707 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700708 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800709
710 event_loop_factory_->DisableForwarding(remapped_channel);
711 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700712
713 // If we are replaying a log, we don't want a bunch of redundant messages
714 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700715 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800716 }
Austin Schuh891214d2021-11-11 20:35:02 -0800717
718 // Write pseudo start times out to file now that we are all setup.
719 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700720}
721
722void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
723 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800724 StartAfterRegister(event_loop_factory);
725}
726
727void LogReader::StartAfterRegister(
728 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700729 // We want to start the log file at the last start time of the log files
730 // from all the nodes. Compute how long each node's simulation needs to run
731 // to move time to this point.
732 distributed_clock::time_point start_time = distributed_clock::min_time;
733
734 // TODO(austin): We want an "OnStart" callback for each node rather than
735 // running until the last node.
736
737 for (std::unique_ptr<State> &state : states_) {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700738 CHECK(state);
Austin Schuh58646e22021-08-23 23:51:46 -0700739 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700740 << " for node '" << MaybeNodeName(state->node()) << "' now "
Austin Schuh58646e22021-08-23 23:51:46 -0700741 << state->monotonic_now();
742 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
743 continue;
744 }
745 // And start computing the start time on the distributed clock now that
746 // that works.
747 start_time = std::max(
748 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
749 }
750
751 // TODO(austin): If a node doesn't have a start time, we might not queue
752 // enough. If this happens, we'll explode with a frozen error eventually.
753
754 CHECK_GE(start_time, distributed_clock::epoch())
755 << ": Hmm, we have a node starting before the start of time. Offset "
756 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800757
Austin Schuhdda74ec2021-01-03 19:30:37 -0800758 {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800759 VLOG(1) << "Running until " << start_time << " in Register";
760 event_loop_factory_->RunFor(start_time.time_since_epoch());
761 VLOG(1) << "At start time";
Austin Schuhdda74ec2021-01-03 19:30:37 -0800762 }
Austin Schuh92547522019-12-28 14:33:43 -0800763
Austin Schuh8bd96322020-02-13 21:18:22 -0800764 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700765 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700766 if (state->realtime_start_time(0) != realtime_clock::min_time) {
767 state->SetRealtimeOffset(state->monotonic_start_time(0),
768 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700769 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700770 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700771 << " for node '" << MaybeNodeName(state->event_loop()->node())
772 << "' now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700773 }
774
775 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800776 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800777 }
778}
779
Austin Schuh2f8fd752020-09-01 22:38:28 -0700780message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800781 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800782 if (filters_) {
783 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800784 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800785 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800786}
787
James Kuszmaul09632422022-05-25 15:56:19 -0700788// TODO(jkuszmaul): Make in-line modifications to
789// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
790// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800791void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700792 filters_ =
793 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
794 event_loop->configuration(), logged_configuration(),
795 log_files_[0].boots, FLAGS_skip_order_validation,
796 chrono::duration_cast<chrono::nanoseconds>(
797 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
798
799 std::vector<TimestampMapper *> timestamp_mappers;
800 for (const Node *node : configuration::GetNodes(configuration())) {
801 const size_t node_index =
802 configuration::GetNodeIndex(configuration(), node);
803 std::vector<LogParts> filtered_parts = FilterPartsForNode(
804 log_files_, node != nullptr ? node->name()->string_view() : "");
805
806 states_[node_index] = std::make_unique<State>(
807 filtered_parts.size() == 0u
808 ? nullptr
809 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700810 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600811 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node),
812 before_send_callbacks_);
James Kuszmaul09632422022-05-25 15:56:19 -0700813 State *state = states_[node_index].get();
814
815 state->SetChannelCount(logged_configuration()->channels()->size());
816 timestamp_mappers.emplace_back(state->timestamp_mapper());
817 }
818
819 filters_->SetTimestampMappers(std::move(timestamp_mappers));
820
821 for (const Node *node : configuration::GetNodes(configuration())) {
822 const size_t node_index =
823 configuration::GetNodeIndex(configuration(), node);
824 State *state = states_[node_index].get();
825 for (const Node *other_node : configuration::GetNodes(configuration())) {
826 const size_t other_node_index =
827 configuration::GetNodeIndex(configuration(), other_node);
828 State *other_state = states_[other_node_index].get();
829 if (other_state != state) {
830 state->AddPeer(other_state);
831 }
832 }
833 }
834 for (const Node *node : configuration::GetNodes(configuration())) {
835 if (node == nullptr || node->name()->string_view() ==
836 event_loop->node()->name()->string_view()) {
837 Register(event_loop, event_loop->node());
838 } else {
839 Register(nullptr, node);
840 }
841 }
Austin Schuh58646e22021-08-23 23:51:46 -0700842}
843
844void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800845 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700846 states_[configuration::GetNodeIndex(configuration(), node)].get();
847
848 // If we didn't find any log files with data in them, we won't ever get a
849 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700850 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700851 return;
852 }
James Kuszmaul09632422022-05-25 15:56:19 -0700853
854 if (event_loop != nullptr) {
855 ++live_nodes_;
856 }
Austin Schuh58646e22021-08-23 23:51:46 -0700857
858 if (event_loop_factory_ != nullptr) {
859 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
860 [this, event_loop, node]() {
861 RegisterDuringStartup(event_loop, node);
862 });
863 } else {
864 RegisterDuringStartup(event_loop, node);
865 }
866}
867
868void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700869 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700870 CHECK(event_loop->configuration() == configuration());
871 }
872
873 State *state =
874 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800875
James Kuszmaul09632422022-05-25 15:56:19 -0700876 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800877 state->ClearTimeFlags();
878 }
879
Austin Schuh858c9f32020-08-31 16:56:12 -0700880 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800881
Tyler Chatow67ddb032020-01-12 14:30:04 -0800882 // We don't run timing reports when trying to print out logged data, because
883 // otherwise we would end up printing out the timing reports themselves...
884 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700885 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700886 event_loop->SkipTimingReport();
887 event_loop->SkipAosLog();
888 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800889
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700890 for (size_t logged_channel_index = 0;
891 logged_channel_index < logged_configuration()->channels()->size();
892 ++logged_channel_index) {
893 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700894 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700895 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800896
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700897 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700898 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700899
900 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700901
Austin Schuh58646e22021-08-23 23:51:46 -0700902 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
903 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700904 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700905 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800906
Austin Schuh58646e22021-08-23 23:51:46 -0700907 // We've got a message which is being forwarded to this node.
908 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700909
910 source_state =
911 states_[configuration::GetNodeIndex(configuration(), source_node)]
912 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800913 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700914
Austin Schuh58646e22021-08-23 23:51:46 -0700915 // We are the source, and it is forwarded.
916 const bool is_forwarded =
917 configuration::ChannelIsSendableOnNode(channel, node) &&
918 configuration::ConnectionCount(channel);
919
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700920 state->SetChannel(
921 logged_channel_index,
922 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700923 event_loop && logged &&
924 configuration::ChannelIsReadableOnNode(channel, node)
925 ? event_loop->MakeRawSender(channel)
926 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700927 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700928
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700929 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700930 const Node *source_node = configuration::GetNode(
931 configuration(), channel->source_node()->string_view());
932
933 for (const Connection *connection : *channel->destination_nodes()) {
934 const bool delivery_time_is_logged =
935 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
936 source_node);
937
938 if (delivery_time_is_logged) {
939 State *destination_state =
940 states_[configuration::GetNodeIndex(
941 configuration(), connection->name()->string_view())]
942 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700943 if (destination_state) {
944 destination_state->SetRemoteTimestampSender(
945 logged_channel_index,
946 event_loop ? state->RemoteTimestampSender(channel, connection)
947 : nullptr);
948 }
Austin Schuh58646e22021-08-23 23:51:46 -0700949 }
950 }
951 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800952 }
953
Austin Schuh58646e22021-08-23 23:51:46 -0700954 if (!event_loop) {
955 state->ClearRemoteTimestampSenders();
956 state->set_timer_handler(nullptr);
957 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800958 return;
959 }
960
Austin Schuh858c9f32020-08-31 16:56:12 -0700961 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700962 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800963 --live_nodes_;
Alexei Strots036d84e2023-05-03 16:05:12 -0700964 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
965 << "' down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700966 if (exit_on_finish_ && live_nodes_ == 0 &&
967 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700968 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800969 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800970 return;
971 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700972
Austin Schuhdda74ec2021-01-03 19:30:37 -0800973 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700974
975 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
976 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800977
Austin Schuhe309d2a2019-11-29 13:25:21 -0800978 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700979 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700980 if (event_loop_factory_ != nullptr) {
981 // Only enforce exact timing in simulation.
982 if (!FLAGS_skip_order_validation) {
983 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
984 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
985 << monotonic_now << " trying to send "
986 << timestamped_message.monotonic_event_time << " failure "
987 << state->DebugString();
988 } else if (BootTimestamp{.boot = state->boot_count(),
989 .time = monotonic_now} !=
990 timestamped_message.monotonic_event_time) {
991 LOG(WARNING) << "Check failed: monotonic_now == "
992 "timestamped_message.monotonic_event_time) ("
993 << monotonic_now << " vs. "
994 << timestamped_message.monotonic_event_time
995 << "): " << FlatbufferToJson(state->event_loop()->node())
996 << " Now " << monotonic_now << " trying to send "
997 << timestamped_message.monotonic_event_time << " failure "
998 << state->DebugString();
999 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001000 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001001
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001002 if (timestamped_message.monotonic_event_time.time >
1003 state->monotonic_start_time(
1004 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -07001005 event_loop_factory_ != nullptr ||
1006 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001007 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001008 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001009 BootTimestamp::min_time() &&
1010 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001011 // Confirm that the message was sent on the sending node before the
1012 // destination node (this node). As a proxy, do this by making sure
1013 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001014 //
1015 // TODO(austin): <= means that the cause message (which we know) could
1016 // happen after the effect even though we know they are at the same
1017 // time. I doubt anyone will notice for a bit, but we should really
1018 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001019 BootTimestamp monotonic_remote_now =
1020 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001021 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001022 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001023 monotonic_remote_now.boot)
1024 << state->event_loop()->node()->name()->string_view() << " to "
1025 << state->remote_node(timestamped_message.channel_index)
1026 ->name()
1027 ->string_view()
1028 << " while trying to send a message on "
1029 << configuration::CleanedChannelToString(
1030 logged_configuration()->channels()->Get(
1031 timestamped_message.channel_index))
1032 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001033 CHECK_LE(timestamped_message.monotonic_remote_time,
1034 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001035 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001036 << state->remote_node(timestamped_message.channel_index)
1037 ->name()
1038 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001039 << " while trying to send a message on "
1040 << configuration::CleanedChannelToString(
1041 logged_configuration()->channels()->Get(
1042 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001043 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001044 } else if (monotonic_remote_now.boot !=
1045 timestamped_message.monotonic_remote_time.boot) {
1046 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1047 << " vs "
1048 << timestamped_message.monotonic_remote_time.boot;
1049 } else if (timestamped_message.monotonic_remote_time >
1050 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001051 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001052 << "Check failed: timestamped_message.monotonic_remote_time < "
1053 "state->monotonic_remote_now(timestamped_message.channel_"
1054 "index) ("
1055 << timestamped_message.monotonic_remote_time << " vs. "
1056 << state->monotonic_remote_now(
1057 timestamped_message.channel_index)
1058 << ") " << state->event_loop()->node()->name()->string_view()
1059 << " to "
1060 << state->remote_node(timestamped_message.channel_index)
1061 ->name()
1062 ->string_view()
1063 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 << " ("
1065 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001066 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001067 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001068 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001069 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001070 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001071 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001072 << ") " << state->DebugString();
1073 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001074 }
1075
Austin Schuh15649d62019-12-28 16:36:38 -08001076 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001077 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001078 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001079
Alexei Strots036d84e2023-05-03 16:05:12 -07001080 VLOG(1) << "For node '" << MaybeNodeName(state->event_loop()->node())
1081 << "' sending at " << timestamped_message.monotonic_event_time
1082 << " : " << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001083 // TODO(austin): std::move channel_data in and make that efficient in
1084 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001085 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001086 } else if (state->found_last_message() ||
1087 (!ignore_missing_data_ &&
1088 // When starting up, we can have data which was sent before
1089 // the log starts, but the timestamp was after the log
1090 // starts. This is unreasonable to avoid, so ignore the
1091 // missing data.
1092 timestamped_message.monotonic_remote_time.time >=
1093 state->monotonic_remote_start_time(
1094 timestamped_message.monotonic_remote_time.boot,
1095 timestamped_message.channel_index) &&
1096 !FLAGS_skip_missing_forwarding_entries)) {
1097 if (!state->found_last_message()) {
1098 // We've found a timestamp without data that we expect to have data
1099 // for. This likely means that we are at the end of the log file.
1100 // Record it and CHECK that in the rest of the log file, we don't find
1101 // any more data on that channel. Not all channels will end at the
1102 // same point in time since they can be in different files.
1103 VLOG(1) << "Found the last message on channel "
1104 << timestamped_message.channel_index << ", "
1105 << configuration::CleanedChannelToString(
1106 logged_configuration()->channels()->Get(
1107 timestamped_message.channel_index))
Alexei Strots036d84e2023-05-03 16:05:12 -07001108 << " on node '" << MaybeNodeName(state->event_loop()->node())
1109 << "' at " << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001110
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001111 // The user might be working with log files from 1 node but forgot to
1112 // configure the infrastructure to log data for a remote channel on
1113 // that node. That can be very hard to debug, even though the log
1114 // reader is doing the right thing. At least log a warning in that
1115 // case and tell the user what is happening so they can either update
1116 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001117 const std::vector<std::string> logger_nodes =
1118 FindLoggerNodes(log_files_);
1119 if (logger_nodes.size()) {
1120 // We have old logs which don't have the logger nodes logged. In
1121 // that case, we can't be helpful :(
1122 bool data_logged = false;
1123 const Channel *channel = logged_configuration()->channels()->Get(
1124 timestamped_message.channel_index);
1125 for (const std::string &node : logger_nodes) {
1126 data_logged |=
1127 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1128 }
1129 if (!data_logged) {
1130 LOG(WARNING) << "Got a timestamp without any logfiles which "
1131 "could contain data for channel "
1132 << configuration::CleanedChannelToString(channel);
1133 LOG(WARNING) << "Only have logs logged on ["
1134 << absl::StrJoin(logger_nodes, ", ") << "]";
1135 LOG(WARNING)
1136 << "Dropping the rest of the data on "
1137 << state->event_loop()->node()->name()->string_view();
1138 LOG(WARNING)
1139 << "Consider using --skip_missing_forwarding_entries to "
1140 "bypass this, update your config to log it, or add data "
1141 "from one of the nodes it is logged on.";
1142 }
1143 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001144 // Now that we found the end of one channel, artificially stop the
1145 // rest by setting the found_last_message bit. It is confusing when
1146 // part of your data gets replayed but not all. The rest of them will
1147 // get dropped as they are replayed to keep memory usage down.
1148 state->SetFoundLastMessage(true);
1149
1150 // Vector storing if we've seen a nullptr message or not per channel.
1151 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001152 }
1153
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001154 // Make sure that once we have seen the last message on a channel,
1155 // data doesn't start back up again. If the user wants to play
1156 // through events like this, they can set
1157 // --skip_missing_forwarding_entries or ignore_missing_data_.
1158 if (timestamped_message.data == nullptr) {
1159 state->set_last_message(timestamped_message.channel_index);
1160 } else {
1161 if (state->last_message(timestamped_message.channel_index)) {
1162 LOG(FATAL) << "Found missing data in the middle of the log file on "
1163 "channel "
1164 << timestamped_message.channel_index << " "
1165 << configuration::StrippedChannelToString(
1166 logged_configuration()->channels()->Get(
1167 timestamped_message.channel_index))
1168 << " " << timestamped_message << " "
1169 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001170 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001171 }
Austin Schuh92547522019-12-28 14:33:43 -08001172 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001173 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001174 LOG(WARNING)
1175 << "Not sending data from before the start of the log file. "
1176 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1177 .count()
1178 << " start "
1179 << monotonic_start_time(state->node()).time_since_epoch().count()
1180 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001181 }
1182
James Kuszmaula16a7912022-06-17 10:58:12 -07001183 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001184 if (next_time != BootTimestamp::max_time()) {
1185 if (next_time.boot != state->boot_count()) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001186 VLOG(1) << "Next message for node '"
Austin Schuh58646e22021-08-23 23:51:46 -07001187 << MaybeNodeName(state->event_loop()->node())
Alexei Strots036d84e2023-05-03 16:05:12 -07001188 << "' is on the next boot, " << next_time << " now is "
Austin Schuh58646e22021-08-23 23:51:46 -07001189 << state->monotonic_now();
1190 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001191 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001192 return;
1193 }
James Kuszmaul09632422022-05-25 15:56:19 -07001194 if (event_loop_factory_ != nullptr) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001195 VLOG(1) << "Scheduling for node '"
1196 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1197 << next_time.time << "("
James Kuszmaul09632422022-05-25 15:56:19 -07001198 << state->ToDistributedClock(next_time.time)
1199 << " distributed), now is " << state->monotonic_now();
1200 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001201 VLOG(1) << "Scheduling for node '"
1202 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1203 << next_time.time << ", now is " << state->monotonic_now();
James Kuszmaul09632422022-05-25 15:56:19 -07001204 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001205 // TODO(james): This can result in negative times getting passed-through
1206 // in realtime replay.
Philipp Schradera6712522023-07-05 20:25:11 -07001207 state->Schedule(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001208 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001209 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1210 << "': No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001211 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001212 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001213 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001214 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001215 // Doesn't apply to single-EventLoop replay since the watchers in question
1216 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001217 if (event_loop_factory_ != nullptr) {
Philipp Schradera6712522023-07-05 20:25:11 -07001218 state->Schedule(monotonic_now + event_loop_factory_->send_delay() +
1219 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001220 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001221 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001222
Alexei Strots036d84e2023-05-03 16:05:12 -07001223 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1224 << "': Done sending at "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001225 << state->event_loop()->context().monotonic_event_time << " now "
1226 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001227 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001228
James Kuszmaula16a7912022-06-17 10:58:12 -07001229 state->SeedSortedMessages();
1230
1231 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001232 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001233 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1234 if (start_time_ != realtime_clock::min_time) {
1235 state->SetStartTimeFlag(start_time_);
1236 }
1237 if (end_time_ != realtime_clock::max_time) {
1238 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001239 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001240 }
Austin Schuh58646e22021-08-23 23:51:46 -07001241 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001242 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001243 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001244 // Queue up messages and then set clock offsets (we don't want to set
1245 // clock offsets before we've done the work of getting the first messages
1246 // primed).
1247 state->QueueThreadUntil(
1248 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1249 std::chrono::duration<double>(
1250 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001251 state->MaybeSetClockOffset();
Philipp Schradera6712522023-07-05 20:25:11 -07001252 state->Schedule(next_time.time);
1253 state->SetUpStartupTimer();
Austin Schuh58646e22021-08-23 23:51:46 -07001254 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001255 }
1256}
1257
Austin Schuhe33c08d2022-02-03 18:15:21 -08001258void LogReader::SetEndTime(std::string end_time) {
1259 if (end_time.empty()) {
1260 SetEndTime(realtime_clock::max_time);
1261 } else {
1262 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1263 aos::realtime_clock::FromString(end_time);
1264 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1265 << "'. Expected a date in the format of "
1266 "2021-01-15_15-30-35.000000000.";
1267 SetEndTime(*parsed_end_time);
1268 }
1269}
1270
1271void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1272 end_time_ = end_time;
1273}
1274
1275void LogReader::SetStartTime(std::string start_time) {
1276 if (start_time.empty()) {
1277 SetStartTime(realtime_clock::min_time);
1278 } else {
1279 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1280 aos::realtime_clock::FromString(start_time);
1281 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1282 << "'. Expected a date in the format of "
1283 "2021-01-15_15-30-35.000000000.";
1284 SetStartTime(*parsed_start_time);
1285 }
1286}
1287
1288void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1289 start_time_ = start_time;
1290}
1291
Austin Schuhe309d2a2019-11-29 13:25:21 -08001292void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001293 // Make sure that things get destroyed in the correct order, rather than
1294 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001295 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001296 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001297 }
Austin Schuh92547522019-12-28 14:33:43 -08001298
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001299 event_loop_factory_unique_ptr_.reset();
1300 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001301}
1302
James Kuszmaul53da7f32022-09-11 11:11:55 -07001303namespace {
1304// Checks if the specified channel name/type exists in the config and, depending
1305// on the value of conflict_handling, calls conflict_handler or just dies.
1306template <typename F>
1307void CheckAndHandleRemapConflict(std::string_view new_name,
1308 std::string_view new_type,
1309 const Configuration *config,
1310 LogReader::RemapConflict conflict_handling,
1311 F conflict_handler) {
1312 const Channel *existing_channel =
1313 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1314 if (existing_channel != nullptr) {
1315 switch (conflict_handling) {
1316 case LogReader::RemapConflict::kDisallow:
1317 LOG(FATAL)
1318 << "Channel "
1319 << configuration::StrippedChannelToString(existing_channel)
1320 << " is already used--you can't remap a logged channel to it.";
1321 break;
1322 case LogReader::RemapConflict::kCascade:
1323 LOG(INFO) << "Automatically remapping "
1324 << configuration::StrippedChannelToString(existing_channel)
1325 << " to avoid conflicts.";
1326 conflict_handler();
1327 break;
1328 }
1329 }
1330}
1331} // namespace
1332
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001333void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001334 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001335 std::string_view new_type,
1336 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001337 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1338 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001339}
1340
Austin Schuh01b4c352020-09-21 23:09:39 -07001341void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1342 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001343 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001344 std::string_view new_type,
1345 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001346 if (node != nullptr) {
1347 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1348 }
1349 if (replay_channels_ != nullptr) {
1350 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1351 std::make_pair(std::string{name}, std::string{type})) !=
1352 replay_channels_->end())
1353 << "Attempted to remap channel " << name << " " << type
1354 << " which is not included in the replay channels passed to LogReader.";
1355 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001356 const Channel *remapped_channel =
1357 configuration::GetChannel(logged_configuration(), name, type, "", node);
1358 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1359 << "\", \"type\": \"" << type << "\"}";
1360 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1361 << "\"}";
1362 VLOG(1) << "Remapped "
1363 << aos::configuration::StrippedChannelToString(remapped_channel);
1364
1365 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1366 // we want it to degrade if the heuristics fail to just work.
1367 //
1368 // The easiest way to do this is going to be incredibly specific and verbose.
1369 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1370 // /original/0/spray. Then, create a map from /original/spray to
1371 // /original/0/spray for just the type we were asked for.
1372 if (name != remapped_channel->name()->string_view()) {
1373 MapT new_map;
1374 new_map.match = std::make_unique<ChannelT>();
1375 new_map.match->name = absl::StrCat(add_prefix, name);
1376 new_map.match->type = type;
1377 if (node != nullptr) {
1378 new_map.match->source_node = node->name()->str();
1379 }
1380 new_map.rename = std::make_unique<ChannelT>();
1381 new_map.rename->name =
1382 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1383 maps_.emplace_back(std::move(new_map));
1384 }
1385
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001386 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001387 const size_t channel_index =
1388 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1389 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1390 << "Already remapped channel "
1391 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001392
1393 RemappedChannel remapped_channel_struct;
1394 remapped_channel_struct.remapped_name =
1395 std::string(add_prefix) +
1396 std::string(remapped_channel->name()->string_view());
1397 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001398 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1399 CheckAndHandleRemapConflict(
1400 remapped_channel_struct.remapped_name, remapped_type,
1401 remapped_configuration_, conflict_handling,
1402 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1403 conflict_handling]() {
1404 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1405 node, add_prefix, "", conflict_handling);
1406 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001407 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001408 MakeRemappedConfig();
1409}
1410
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001411void LogReader::RenameLoggedChannel(const std::string_view name,
1412 const std::string_view type,
1413 const std::string_view new_name,
1414 const std::vector<MapT> &add_maps) {
1415 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1416}
1417
1418void LogReader::RenameLoggedChannel(const std::string_view name,
1419 const std::string_view type,
1420 const Node *const node,
1421 const std::string_view new_name,
1422 const std::vector<MapT> &add_maps) {
1423 if (node != nullptr) {
1424 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1425 }
1426 // First find the channel and rename it.
1427 const Channel *remapped_channel =
1428 configuration::GetChannel(logged_configuration(), name, type, "", node);
1429 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1430 << "\", \"type\": \"" << type << "\"}";
1431 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1432 << "\"}";
1433 VLOG(1) << "Remapped "
1434 << aos::configuration::StrippedChannelToString(remapped_channel);
1435
1436 const size_t channel_index =
1437 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1438 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1439 << "Already remapped channel "
1440 << configuration::CleanedChannelToString(remapped_channel);
1441
1442 RemappedChannel remapped_channel_struct;
1443 remapped_channel_struct.remapped_name = new_name;
1444 remapped_channel_struct.new_type.clear();
1445 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1446
1447 // Then add any provided maps.
1448 for (const MapT &map : add_maps) {
1449 maps_.push_back(map);
1450 }
1451
1452 // Finally rewrite the config.
1453 MakeRemappedConfig();
1454}
1455
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001456void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001457 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001458 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001459 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001460 << ": Can't change the mapping after the events are scheduled.";
1461 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001462 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001463
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001464 // If no remapping occurred and we are using the original config, then there
1465 // is nothing interesting to do here.
1466 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001467 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001468 return;
1469 }
1470 // Config to copy Channel definitions from. Use the specified
1471 // replay_configuration_ if it has been provided.
1472 const Configuration *const base_config = replay_configuration_ == nullptr
1473 ? logged_configuration()
1474 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001475
1476 // Create a config with all the channels, but un-sorted/merged. Collect up
1477 // the schemas while we do this. Call MergeConfiguration to sort everything,
1478 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001479
1480 // This is the builder that we use for the config containing all the new
1481 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001482 flatbuffers::FlatBufferBuilder fbb;
1483 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001484 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001485
1486 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1487 << ": Merging logic needs to be updated when the number of channel "
1488 "fields changes.";
1489
1490 // List of schemas.
1491 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1492 // Make sure our new RemoteMessage schema is in there for old logs without it.
1493 schema_map.insert(std::make_pair(
1494 RemoteMessage::GetFullyQualifiedName(),
1495 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1496 message_bridge::RemoteMessageSchema()))));
1497
1498 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001499 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001500 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001501 base_config, logged_configuration()->channels()->Get(pair.first), "",
1502 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001503 channel_offsets.emplace_back(
1504 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001505
1506 if (c->has_destination_nodes()) {
1507 for (const Connection *connection : *c->destination_nodes()) {
1508 switch (connection->timestamp_logger()) {
1509 case LoggerConfig::LOCAL_LOGGER:
1510 case LoggerConfig::NOT_LOGGED:
1511 // There is no timestamp channel associated with this, so ignore it.
1512 break;
1513
1514 case LoggerConfig::REMOTE_LOGGER:
1515 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1516 // We want to make a split timestamp channel regardless of what type
1517 // of log this used to be. No sense propagating the single
1518 // timestamp channel.
1519
1520 CHECK(connection->has_timestamp_logger_nodes());
1521 for (const flatbuffers::String *timestamp_logger_node :
1522 *connection->timestamp_logger_nodes()) {
1523 const Node *node = configuration::GetNode(
1524 logged_configuration(), timestamp_logger_node->string_view());
1525 message_bridge::ChannelTimestampFinder finder(
1526 logged_configuration(), "log_reader", node);
1527
1528 // We are assuming here that all the maps are setup correctly to
1529 // handle arbitrary timestamps. Apply the maps for this node to
1530 // see what name this ends up with.
1531 std::string name = finder.SplitChannelName(
1532 pair.second.remapped_name, c->type()->str(), connection);
1533 std::string unmapped_name = name;
1534 configuration::HandleMaps(logged_configuration()->maps(), &name,
1535 "aos.message_bridge.RemoteMessage",
1536 node);
1537 CHECK_NE(name, unmapped_name)
1538 << ": Remote timestamp channel was not remapped, this is "
1539 "very fishy";
1540 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1541 fbb.CreateString(name);
1542 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1543 fbb.CreateString("aos.message_bridge.RemoteMessage");
1544 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1545 fbb.CreateString(timestamp_logger_node->string_view());
1546
1547 // Now, build a channel. Don't log it, 2 senders, and match the
1548 // source frequency.
1549 Channel::Builder channel_builder(fbb);
1550 channel_builder.add_name(channel_name_offset);
1551 channel_builder.add_type(channel_type_offset);
1552 channel_builder.add_source_node(source_node_offset);
1553 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1554 channel_builder.add_num_senders(2);
1555 if (c->has_frequency()) {
1556 channel_builder.add_frequency(c->frequency());
1557 }
1558 channel_offsets.emplace_back(channel_builder.Finish());
1559 }
1560 break;
1561 }
1562 }
1563 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001564 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001565
Austin Schuh0de30f32020-12-06 12:44:28 -08001566 // Now reconstruct the original channels, translating types as needed
1567 for (const Channel *c : *base_config->channels()) {
1568 // Search for a mapping channel.
1569 std::string_view new_type = "";
1570 for (auto &pair : remapped_channels_) {
1571 const Channel *const remapped_channel =
1572 logged_configuration()->channels()->Get(pair.first);
1573 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1574 remapped_channel->type()->string_view() == c->type()->string_view()) {
1575 new_type = pair.second.new_type;
1576 break;
1577 }
1578 }
1579
1580 // Copy everything over.
1581 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1582
1583 // Add the schema if it doesn't exist.
1584 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1585 CHECK(c->has_schema());
1586 schema_map.insert(std::make_pair(c->type()->string_view(),
1587 RecursiveCopyFlatBuffer(c->schema())));
1588 }
1589 }
1590
1591 // The MergeConfiguration API takes a vector, not a map. Convert.
1592 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1593 while (!schema_map.empty()) {
1594 schemas.emplace_back(std::move(schema_map.begin()->second));
1595 schema_map.erase(schema_map.begin());
1596 }
1597
1598 // Create the Configuration containing the new channels that we want to add.
1599 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1600 channels_offset =
1601 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1602
1603 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001604 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001605 if (base_config->maps()) {
1606 for (const Map *map : *base_config->maps()) {
1607 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1608 }
1609 }
1610
1611 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001612 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001613 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001614 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001615 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001616 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1617 if (!map.match->type.empty()) {
1618 match_type_offset = fbb.CreateString(map.match->type);
1619 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001620 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1621 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001622 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001623 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001624 CHECK(!map.rename->name.empty());
1625 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1626 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001627 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001628 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001629 if (!match_type_offset.IsNull()) {
1630 match_builder.add_type(match_type_offset);
1631 }
1632 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001633 match_builder.add_source_node(match_source_node_offset);
1634 }
1635 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1636
Austin Schuh0de30f32020-12-06 12:44:28 -08001637 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001638 rename_builder.add_name(rename_name_offset);
1639 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1640
Austin Schuh0de30f32020-12-06 12:44:28 -08001641 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001642 map_builder.add_match(match_offset);
1643 map_builder.add_rename(rename_offset);
1644 map_offsets.emplace_back(map_builder.Finish());
1645 }
1646
Austin Schuh0de30f32020-12-06 12:44:28 -08001647 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1648 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001649
Austin Schuh0de30f32020-12-06 12:44:28 -08001650 // And copy everything else over.
1651 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1652 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1653
1654 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1655 applications_offset =
1656 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1657
1658 // Now insert everything else in unmodified.
1659 ConfigurationBuilder configuration_builder(fbb);
1660 if (!channels_offset.IsNull()) {
1661 configuration_builder.add_channels(channels_offset);
1662 }
1663 if (!maps_offsets.IsNull()) {
1664 configuration_builder.add_maps(maps_offsets);
1665 }
1666 if (!nodes_offset.IsNull()) {
1667 configuration_builder.add_nodes(nodes_offset);
1668 }
1669 if (!applications_offset.IsNull()) {
1670 configuration_builder.add_applications(applications_offset);
1671 }
1672
1673 if (base_config->has_channel_storage_duration()) {
1674 configuration_builder.add_channel_storage_duration(
1675 base_config->channel_storage_duration());
1676 }
1677
1678 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1679 << ": Merging logic needs to be updated when the number of configuration "
1680 "fields changes.";
1681
1682 fbb.Finish(configuration_builder.Finish());
1683
1684 // Clean it up and return it! By using MergeConfiguration here, we'll
1685 // actually get a deduplicated config for free too.
1686 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1687 configuration::MergeConfiguration(
1688 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1689
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001690 remapped_configuration_buffer_ =
1691 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001692 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001693
1694 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001695
1696 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001697}
1698
Naman Guptacf6d4422023-03-01 11:41:00 -08001699std::unique_ptr<const ReplayChannelIndices>
1700LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001701 if (replay_channels_ == nullptr) {
1702 return nullptr;
1703 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001704 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1705 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001706 for (auto const &channel : *replay_channels_) {
1707 const Channel *ch = configuration::GetChannel(
1708 logged_configuration(), channel.first, channel.second, "", node);
1709 if (ch == nullptr) {
1710 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1711 << " not found in configuration for node: "
1712 << node->name()->string_view() << " Skipping ...";
1713 continue;
1714 }
1715 const size_t channel_index =
1716 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001717 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001718 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001719 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1720 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001721 }
1722}
1723
Austin Schuh1c227352021-09-17 12:53:54 -07001724std::vector<const Channel *> LogReader::RemappedChannels() const {
1725 std::vector<const Channel *> result;
1726 result.reserve(remapped_channels_.size());
1727 for (auto &pair : remapped_channels_) {
1728 const Channel *const logged_channel =
1729 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1730
1731 auto channel_iterator = std::lower_bound(
1732 remapped_configuration_->channels()->cbegin(),
1733 remapped_configuration_->channels()->cend(),
1734 std::make_pair(std::string_view(pair.second.remapped_name),
1735 logged_channel->type()->string_view()),
1736 CompareChannels);
1737
1738 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1739 CHECK(EqualsChannels(
1740 *channel_iterator,
1741 std::make_pair(std::string_view(pair.second.remapped_name),
1742 logged_channel->type()->string_view())));
1743 result.push_back(*channel_iterator);
1744 }
1745 return result;
1746}
1747
Austin Schuh6f3babe2020-01-26 20:34:50 -08001748const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001749 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001750 const Channel *channel) {
1751 std::string_view channel_name = channel->name()->string_view();
1752 std::string_view channel_type = channel->type()->string_view();
1753 const int channel_index =
1754 configuration::ChannelIndex(logged_configuration(), channel);
1755 // If the channel is remapped, find the correct channel name to use.
1756 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001757 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001758 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001759 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001760 }
1761
Austin Schuhee711052020-08-24 16:06:09 -07001762 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001763 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001764 configuration(), channel_name, channel_type,
1765 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001766
1767 CHECK(remapped_channel != nullptr)
1768 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1769 << channel_type << "\"} because it is not in the provided configuration.";
1770
1771 return remapped_channel;
1772}
1773
James Kuszmaul09632422022-05-25 15:56:19 -07001774LogReader::State::State(
1775 std::unique_ptr<TimestampMapper> timestamp_mapper,
1776 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001777 std::function<void()> notice_realtime_end, const Node *node,
1778 LogReader::State::ThreadedBuffering threading,
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001779 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices,
1780 const std::vector<std::function<void(void *message)>>
1781 &before_send_callbacks)
James Kuszmaul09632422022-05-25 15:56:19 -07001782 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001783 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001784 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001785 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001786 threading_(threading),
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001787 replay_channel_indices_(std::move(replay_channel_indices)),
1788 before_send_callbacks_(before_send_callbacks) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001789 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1790 // with this node. If there are no log parts for the node, there will be no
1791 // log data, and so we do not need to worry about the replay channel filters.
1792 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001793 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001794 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001795 const TimestampedMessage &message) -> bool {
1796 auto const begin = filter->cbegin();
1797 auto const end = filter->cend();
1798 // TODO: benchmark strategies for channel_index matching
1799 return std::binary_search(begin, end, message.channel_index);
1800 });
1801 }
1802}
Austin Schuh287d43d2020-12-04 20:19:33 -08001803
1804void LogReader::State::AddPeer(State *peer) {
1805 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1806 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1807 }
1808}
Austin Schuh858c9f32020-08-31 16:56:12 -07001809
Austin Schuh58646e22021-08-23 23:51:46 -07001810void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001811 NodeEventLoopFactory *node_event_loop_factory,
1812 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001813 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001814 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001815}
1816
1817void LogReader::State::SetChannelCount(size_t count) {
1818 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001819 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001820 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001821 channel_source_state_.resize(count);
1822 factory_channel_index_.resize(count);
1823 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001824}
1825
Austin Schuh58646e22021-08-23 23:51:46 -07001826void LogReader::State::SetRemoteTimestampSender(
1827 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1828 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1829}
1830
Austin Schuh858c9f32020-08-31 16:56:12 -07001831void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001832 size_t logged_channel_index, size_t factory_channel_index,
1833 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001834 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1835 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001836 channels_[logged_channel_index] = std::move(sender);
1837 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001838 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001839
Austin Schuh58646e22021-08-23 23:51:46 -07001840 if (is_forwarded) {
1841 queue_index_map_[logged_channel_index] =
1842 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001843 }
1844
1845 factory_channel_index_[logged_channel_index] = factory_channel_index;
1846}
1847
James Kuszmaula16a7912022-06-17 10:58:12 -07001848void LogReader::State::TrackMessageSendTiming(
1849 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1850 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1851 return;
1852 }
1853
1854 timing::MessageTimingT sample;
1855 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1856 sender.channel());
1857 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1858 sample.actual_send_time =
1859 sender.monotonic_sent_time().time_since_epoch().count();
1860 sample.send_time_error = aos::time::DurationInSeconds(
1861 expected_send_time - sender.monotonic_sent_time());
1862 send_timings_.push_back(sample);
1863
1864 // Somewhat arbitrarily send out timing information in batches of 100. No need
1865 // to create excessive overhead in regenerated logfiles.
1866 // TODO(james): The overhead may be fine.
1867 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1868 CHECK(timing_statistics_sender_.valid());
1869 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1870 SendMessageTimings();
1871 }
1872}
1873
1874void LogReader::State::SendMessageTimings() {
1875 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1876 return;
1877 }
1878 auto builder = timing_statistics_sender_.MakeBuilder();
1879 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1880 for (const auto &timing : send_timings_) {
1881 timing_offsets.push_back(
1882 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1883 }
1884 send_timings_.clear();
1885 flatbuffers::Offset<
1886 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1887 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1888 timing::ReplayTiming::Builder timing_builder =
1889 builder.MakeBuilder<timing::ReplayTiming>();
1890 timing_builder.add_messages(timings_offset);
1891 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1892}
1893
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001894bool LogReader::State::Send(const TimestampedMessage &&timestamped_message) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001895 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001896 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001897 uint32_t remote_queue_index = 0xffffffff;
1898
Austin Schuh287d43d2020-12-04 20:19:33 -08001899 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001900 State *source_state =
1901 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001902 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001903 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001904 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001905
Austin Schuh9942bae2021-01-07 22:06:44 -08001906 struct SentTimestamp {
1907 monotonic_clock::time_point monotonic_event_time;
1908 uint32_t queue_index;
1909 } search;
1910
Austin Schuh58646e22021-08-23 23:51:46 -07001911 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1912 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001913 search.monotonic_event_time =
1914 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001915 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001916
1917 // Find the sent time if available.
1918 auto element = std::lower_bound(
1919 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001920 [](ContiguousSentTimestamp a, SentTimestamp b) {
1921 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001922 return true;
1923 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001924 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001925 return false;
1926 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001927
1928 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 return true;
1930 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001931 if (a.starting_queue_index >= b.queue_index) {
1932 return false;
1933 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001934
Austin Schuh9942bae2021-01-07 22:06:44 -08001935 // If it isn't clearly below or above, it is below. Since we return
1936 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001937 return false;
1938 });
1939
1940 // TODO(austin): Be a bit more principled here, but we will want to do that
1941 // after the logger rewrite. We hit this when one node finishes, but the
1942 // other node isn't done yet. So there is no send time, but there is a
1943 // receive time.
1944 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001945 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1946 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001947
1948 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001949 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001950 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001951 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001952 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001953 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001954 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001955 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001956
Austin Schuh58646e22021-08-23 23:51:46 -07001957 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001958 element->actual_queue_index -
1959 element->starting_queue_index;
1960 } else {
1961 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001962 }
Austin Schuh58646e22021-08-23 23:51:46 -07001963 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1964 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001965 }
1966
James Kuszmaul09632422022-05-25 15:56:19 -07001967 if (event_loop_factory_ != nullptr &&
1968 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1969 multinode_filters_ != nullptr) {
1970 // Sanity check that we are using consistent boot uuids.
1971 State *source_state =
1972 channel_source_state_[timestamped_message.channel_index];
1973 CHECK_EQ(multinode_filters_->boot_uuid(
1974 configuration::GetNodeIndex(event_loop_->configuration(),
1975 source_state->node()),
1976 timestamped_message.monotonic_remote_time.boot),
1977 CHECK_NOTNULL(
1978 CHECK_NOTNULL(
1979 channel_source_state_[timestamped_message.channel_index])
1980 ->event_loop_)
1981 ->boot_uuid());
1982 }
1983
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001984 // Right before sending allow the user to process the message.
1985 if (before_send_callbacks_[timestamped_message.channel_index]) {
1986 // Only channels that are forwarded and sent from this State's node will be
1987 // in the queue_index_map_
1988 if (queue_index_map_[timestamped_message.channel_index]) {
1989 before_send_callbacks_[timestamped_message.channel_index](
1990 timestamped_message.data->mutable_data());
1991 }
1992 }
1993
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001994 // Send! Use the replayed queue index here instead of the logged queue index
1995 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001996 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001997 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001998 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001999 timestamped_message.realtime_remote_time, remote_queue_index,
2000 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07002001 ? CHECK_NOTNULL(multinode_filters_)
2002 ->boot_uuid(configuration::GetNodeIndex(
2003 event_loop_->configuration(),
2004 channel_source_state_[timestamped_message
2005 .channel_index]
2006 ->node()),
2007 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07002008 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07002009 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07002010 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
2011 timestamped_message.monotonic_event_time.time) {
2012 // Only track errors for non-fetched messages.
2013 TrackMessageSendTiming(
2014 *sender,
2015 timestamped_message.monotonic_event_time.time + clock_offset());
2016 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002017
Austin Schuh287d43d2020-12-04 20:19:33 -08002018 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07002019 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08002020 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
2021 // Nothing here, start a range with 0 length.
2022 ContiguousSentTimestamp timestamp;
2023 timestamp.starting_monotonic_event_time =
2024 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002025 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002026 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002027 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002028 timestamp.actual_queue_index = sender->sent_queue_index();
2029 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2030 timestamp);
2031 } else {
2032 // We've got something. See if the next timestamp is still contiguous. If
2033 // so, grow it.
2034 ContiguousSentTimestamp *back =
2035 &queue_index_map_[timestamped_message.channel_index]->back();
2036 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002037 (timestamped_message.queue_index.index -
2038 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002039 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002040 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002041 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002042 } else {
2043 // Otherwise, make a new one.
2044 ContiguousSentTimestamp timestamp;
2045 timestamp.starting_monotonic_event_time =
2046 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002047 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002048 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002049 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002050 timestamp.actual_queue_index = sender->sent_queue_index();
2051 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2052 timestamp);
2053 }
2054 }
2055
2056 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2057 // queue index diverge a couple of elements, which would be a very small
2058 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002059 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2060 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002061 // TODO(james): Currently, If running replay against a single event loop,
2062 // remote timestamps will not get replayed because this code-path only
2063 // gets triggered on the event loop that receives the forwarded message
2064 // that the timestamps correspond to. This code, as written, also doesn't
2065 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002066 State *source_state =
2067 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2068
Austin Schuh969cd602021-01-03 00:09:45 -08002069 flatbuffers::FlatBufferBuilder fbb;
2070 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002071 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2072 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002073
Austin Schuh969cd602021-01-03 00:09:45 -08002074 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002075
2076 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002077 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002078
2079 // Swap the remote and sent metrics. They are from the sender's
2080 // perspective, not the receiver's perspective.
2081 message_header_builder.add_monotonic_sent_time(
2082 sender->monotonic_sent_time().time_since_epoch().count());
2083 message_header_builder.add_realtime_sent_time(
2084 sender->realtime_sent_time().time_since_epoch().count());
2085 message_header_builder.add_queue_index(sender->sent_queue_index());
2086
Austin Schuh58646e22021-08-23 23:51:46 -07002087 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2088 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002089 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002090 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2091 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002092 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002093 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002094
2095 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002096 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002097
Austin Schuh969cd602021-01-03 00:09:45 -08002098 fbb.Finish(message_header_builder.Finish());
2099
2100 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2101 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002102 timestamped_message.monotonic_timestamp_time,
2103 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002104 }
2105
2106 return true;
2107}
2108
Austin Schuh969cd602021-01-03 00:09:45 -08002109LogReader::RemoteMessageSender::RemoteMessageSender(
2110 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2111 : event_loop_(event_loop),
2112 sender_(std::move(sender)),
2113 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2114
2115void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2116 if (remote_timestamps_.empty()) {
2117 CHECK_NOTNULL(timer_);
2118 timer_->Disable();
2119 scheduled_time_ = monotonic_clock::min_time;
2120 return;
2121 }
2122
2123 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2124 CHECK_NOTNULL(timer_);
Philipp Schradera6712522023-07-05 20:25:11 -07002125 timer_->Schedule(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002126 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002127 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2128 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002129 }
2130}
2131
2132void LogReader::RemoteMessageSender::Send(
2133 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002134 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002135 // There are 2 variants of logs.
2136 // 1) Logs without monotonic_timestamp_time
2137 // 2) Logs with monotonic_timestamp_time
2138 //
2139 // As of Jan 2021, we shouldn't have any more logs without
2140 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2141 // the effort of saving.
2142 //
2143 // This gives us 3 cases, 2 of which are undistinguishable.
2144 // 1) Old log without monotonic_timestamp_time.
2145 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2146 // remotely so we actually have monotonic_timestamp_time.
2147 // 3) New log, but the timestamp was logged on the node receiving the message
2148 // so there is no monotonic_timestamp_time.
2149 //
2150 // Our goal when replaying is to accurately reproduce the state of the world
2151 // present when logging. If a timestamp wasn't sent back across the network,
2152 // we shouldn't replay one back across the network.
2153 //
2154 // Given that we don't really care about 1, we can use the presence of the
2155 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2156 // monotonic_timestamp_time, this means the message was logged locally and
2157 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002158 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002159 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002160 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002161
Austin Schuh58646e22021-08-23 23:51:46 -07002162 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2163
Austin Schuhc41d6a82021-07-16 14:49:23 -07002164 remote_timestamps_.emplace(
2165 std::upper_bound(
2166 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002167 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002168 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2169 const Timestamp &timestamp) {
2170 return monotonic_timestamp_time <
2171 timestamp.monotonic_timestamp_time;
2172 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002173 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002174 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002175}
2176
2177void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002178 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2179 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002180 CHECK(!remote_timestamps_.empty());
2181
2182 // Send out all timestamps at the currently scheduled time.
2183 while (remote_timestamps_.front().monotonic_timestamp_time ==
2184 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002185 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2186 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002187 remote_timestamps_.pop_front();
2188 if (remote_timestamps_.empty()) {
2189 break;
2190 }
2191 }
2192 scheduled_time_ = monotonic_clock::min_time;
2193
2194 ScheduleTimestamp();
2195}
2196
2197LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002198 const Channel *channel, const Connection *connection) {
2199 message_bridge::ChannelTimestampFinder finder(event_loop_);
2200 // Look at any pre-created channel/connection pairs.
2201 {
2202 auto it =
2203 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2204 if (it != channel_timestamp_loggers_.end()) {
2205 return it->second.get();
2206 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002207 }
2208
Austin Schuh61e973f2021-02-21 21:43:56 -08002209 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2210 // to.
2211 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2212
2213 {
2214 // See if that has been created before. If so, cache it in
2215 // channel_timestamp_loggers_ and return.
2216 auto it = timestamp_loggers_.find(timestamp_channel);
2217 if (it != timestamp_loggers_.end()) {
2218 CHECK(channel_timestamp_loggers_
2219 .try_emplace(std::make_pair(channel, connection), it->second)
2220 .second);
2221 return it->second.get();
2222 }
2223 }
2224
2225 // Otherwise, make a sender, save it, and cache it.
2226 auto result = channel_timestamp_loggers_.try_emplace(
2227 std::make_pair(channel, connection),
2228 std::make_shared<RemoteMessageSender>(
2229 event_loop()->MakeSender<RemoteMessage>(
2230 timestamp_channel->name()->string_view()),
2231 event_loop()));
2232
2233 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2234 .second);
2235 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002236}
2237
Austin Schuhdda74ec2021-01-03 19:30:37 -08002238TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002239 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002240 if (message_queuer_.has_value()) {
2241 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2242 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2243 message_queuer_->SetState(
2244 message.value().monotonic_event_time +
2245 std::chrono::duration_cast<std::chrono::nanoseconds>(
2246 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2247 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002248 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002249 CHECK(timestamp_mapper_ != nullptr);
2250 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2251 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002252
James Kuszmaula16a7912022-06-17 10:58:12 -07002253 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002254
Alexei Strots036d84e2023-05-03 16:05:12 -07002255 VLOG(2) << "Node '" << MaybeNodeName(event_loop_->node())
2256 << "': PopOldest Popping " << result.monotonic_event_time;
James Kuszmaula16a7912022-06-17 10:58:12 -07002257 timestamp_mapper_->PopFront();
2258 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002259
James Kuszmaula16a7912022-06-17 10:58:12 -07002260 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002261
James Kuszmaula16a7912022-06-17 10:58:12 -07002262 VLOG(1) << "Popped " << result
2263 << configuration::CleanedChannelToString(
2264 event_loop_->configuration()->channels()->Get(
2265 factory_channel_index_[result.channel_index]));
2266 return result;
2267 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002268}
2269
James Kuszmaula16a7912022-06-17 10:58:12 -07002270BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2271 if (!message_queuer_.has_value()) {
2272 return SingleThreadedOldestMessageTime();
2273 }
2274 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2275 if (!message.has_value()) {
2276 return BootTimestamp::max_time();
2277 }
2278 if (message.value().monotonic_event_time.boot == boot_count()) {
2279 ObserveNextMessage(message.value().monotonic_event_time.time,
2280 message.value().realtime_event_time);
2281 }
2282 return message.value().monotonic_event_time;
2283}
2284
2285BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2286 CHECK(!message_queuer_.has_value())
2287 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2288 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002289 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002290 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002291 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002292 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2293 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002294 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002295 }
Alexei Strots036d84e2023-05-03 16:05:12 -07002296 VLOG(2) << "Node '" << MaybeNodeName(node()) << "': oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002297 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002298 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2299 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2300 result_ptr->realtime_event_time);
2301 }
Austin Schuh58646e22021-08-23 23:51:46 -07002302 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002303}
2304
2305void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002306 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002307
Austin Schuhe639ea12021-01-25 13:00:22 -08002308 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2309 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002310}
2311
2312void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002313 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002314 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002315 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002316 for (size_t i = 0; i < channels_.size(); ++i) {
2317 channels_[i].reset();
2318 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002319 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002320 channel_timestamp_loggers_.clear();
2321 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002322 event_loop_unique_ptr_.reset();
2323 event_loop_ = nullptr;
2324 timer_handler_ = nullptr;
2325 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002326 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002327}
2328
Austin Schuhe33c08d2022-02-03 18:15:21 -08002329void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2330 if (start_time != realtime_clock::min_time) {
2331 start_event_notifier_ = std::make_unique<EventNotifier>(
2332 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2333 }
2334}
2335
2336void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2337 if (end_time != realtime_clock::max_time) {
2338 end_event_notifier_ = std::make_unique<EventNotifier>(
2339 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2340 }
2341}
2342
2343void LogReader::State::ObserveNextMessage(
2344 monotonic_clock::time_point monotonic_event,
2345 realtime_clock::time_point realtime_event) {
2346 if (start_event_notifier_) {
2347 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2348 }
2349 if (end_event_notifier_) {
2350 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2351 }
2352}
2353
2354void LogReader::State::ClearTimeFlags() {
2355 start_event_notifier_.reset();
2356 end_event_notifier_.reset();
2357}
2358
2359void LogReader::State::NotifyLogfileStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002360 // If the start_event_notifier_ is set, that means that a realtime start time
2361 // was set manually; when the override is set, we want to delay any startup
2362 // handlers that would've happened before requested start time until that
2363 // start time.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002364 if (start_event_notifier_) {
Philipp Schrader790cb542023-07-05 21:06:52 -07002365 // Only call OnStart() if the start time for this node
2366 // (realtime_start_time())
Austin Schuhe33c08d2022-02-03 18:15:21 -08002367 if (start_event_notifier_->realtime_event_time() >
2368 realtime_start_time(boot_count())) {
2369 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2370 << " > " << realtime_start_time(boot_count());
2371 return;
2372 }
2373 }
2374 if (found_last_message_) {
2375 VLOG(1) << "Last message already found, bailing";
2376 return;
2377 }
2378 RunOnStart();
2379}
2380
2381void LogReader::State::NotifyFlagStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002382 // Should only be called if start_event_notifier_ has been set (which happens
2383 // as part of setting an explicit start time); only call the startup functions
2384 // that occurred *before* the start flag value.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002385 if (start_event_notifier_->realtime_event_time() >=
2386 realtime_start_time(boot_count())) {
2387 RunOnStart();
2388 }
2389}
2390
2391void LogReader::State::NotifyLogfileEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002392 // Don't execute the OnEnd handlers if the logfile was ended artifically
2393 // early.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002394 if (found_last_message_) {
2395 return;
2396 }
2397
James Kuszmaul82c3b512023-07-08 20:25:41 -07002398 // Ensure that we only call OnEnd() if OnStart() was already called for this
2399 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002400 if (!stopped_ && started_) {
2401 RunOnEnd();
2402 }
2403}
2404
2405void LogReader::State::NotifyFlagEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002406 // Ensure that we only call OnEnd() if OnStart() was already called for this
2407 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002408 if (!stopped_ && started_) {
2409 RunOnEnd();
2410 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002411 CHECK(notice_realtime_end_);
2412 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002413 }
2414}
2415
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002416void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002417 if (node_event_loop_factory_ == nullptr) {
2418 // If not running with simulated event loop, set the monotonic clock
2419 // offset.
2420 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2421
2422 if (start_event_notifier_) {
2423 start_event_notifier_->SetClockOffset(clock_offset_);
2424 }
2425 if (end_event_notifier_) {
2426 end_event_notifier_->SetClockOffset(clock_offset_);
2427 }
2428 }
2429}
2430
James Kuszmaulb67409b2022-06-20 16:25:03 -07002431void LogReader::SetRealtimeReplayRate(double replay_rate) {
2432 CHECK(event_loop_factory_ != nullptr)
2433 << ": Can't set replay rate without an event loop factory (have you "
2434 "called Register()?).";
2435 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2436}
2437
James Kuszmaulb11a1502022-07-01 16:02:25 -07002438void LogReader::NoticeRealtimeEnd() {
2439 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2440 --live_nodes_with_realtime_time_end_;
2441 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2442 event_loop_factory_ != nullptr) {
2443 event_loop_factory_->Exit();
2444 }
2445}
2446
Eric Schmiedebergae00e732023-04-12 15:53:17 -06002447bool LogReader::AreStatesInitialized() const {
2448 for (const auto &state : states_) {
2449 if (state) {
2450 return true;
2451 }
2452 }
2453 return false;
2454}
2455
Austin Schuhe309d2a2019-11-29 13:25:21 -08002456} // namespace logger
2457} // namespace aos