blob: af8a4e8ce7a662a9c4d0b28fbec8aea85a2331a7 [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)
Alexei Strots1f51ac72023-05-15 10:14:54 -0700241 : LogReader(LogFilesContainer(SortParts({std::string(filename)})),
242 replay_configuration, 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)
Alexei Strots1f51ac72023-05-15 10:14:54 -0700247 : LogReader(LogFilesContainer(std::move(log_files)), replay_configuration,
248 replay_channels) {}
249
250LogReader::LogReader(LogFilesContainer log_files,
251 const Configuration *replay_configuration,
252 const ReplayChannels *replay_channels)
Austin Schuh287d43d2020-12-04 20:19:33 -0800253 : log_files_(std::move(log_files)),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700254 replay_configuration_(replay_configuration),
255 replay_channels_(replay_channels) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800256 SetStartTime(FLAGS_start_time);
257 SetEndTime(FLAGS_end_time);
258
Austin Schuh0ca51f32020-12-25 21:51:45 -0800259 {
Alexei Strots1f51ac72023-05-15 10:14:54 -0700260 // Log files container validates that log files shared the same config.
261 const Configuration *config = log_files_.config();
262 CHECK_NOTNULL(config);
Austin Schuh0ca51f32020-12-25 21:51:45 -0800263 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800264
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700265 if (replay_channels_ != nullptr) {
266 CHECK(!replay_channels_->empty()) << "replay_channels is empty which means "
267 "no messages will get replayed.";
268 }
269
Austin Schuh6331ef92020-01-07 18:28:09 -0800270 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800271
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700272 // Remap all existing remote timestamp channels. They will be recreated, and
273 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700274 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800275 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
276 "log_reader", node);
277
278 absl::btree_set<std::string_view> remote_nodes;
279
280 for (const Channel *channel : *logged_configuration()->channels()) {
281 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
282 continue;
283 }
284 if (!channel->has_destination_nodes()) {
285 continue;
286 }
287 for (const Connection *connection : *channel->destination_nodes()) {
288 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
289 node)) {
290 // Start by seeing if the split timestamp channels are being used for
291 // this message. If so, remap them.
292 const Channel *timestamp_channel = configuration::GetChannel(
293 logged_configuration(),
294 finder.SplitChannelName(channel, connection),
295 RemoteMessage::GetFullyQualifiedName(), "", node, true);
296
297 if (timestamp_channel != nullptr) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700298 // If for some reason a timestamp channel is not NOT_LOGGED (which
299 // is unusual), then remap the channel so that the replayed channel
300 // doesn't overlap with the special separate replay we do for
301 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800302 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
303 RemapLoggedChannel<RemoteMessage>(
304 timestamp_channel->name()->string_view(), node);
305 }
306 continue;
307 }
308
309 // Otherwise collect this one up as a node to look for a combined
310 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700311 LOG(WARNING) << "Failed to find channel "
312 << finder.SplitChannelName(channel, connection)
313 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800314 remote_nodes.insert(connection->name()->string_view());
315 }
316 }
317 }
318
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700319 std::vector<const Node *> timestamp_logger_nodes =
320 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800321 for (const std::string_view remote_node : remote_nodes) {
322 const std::string channel = finder.CombinedChannelName(remote_node);
323
Austin Schuh0de30f32020-12-06 12:44:28 -0800324 // See if the log file is an old log with MessageHeader channels in it, or
325 // a newer log with RemoteMessage. If we find an older log, rename the
326 // type too along with the name.
327 if (HasChannel<MessageHeader>(channel, node)) {
328 CHECK(!HasChannel<RemoteMessage>(channel, node))
329 << ": Can't have both a MessageHeader and RemoteMessage remote "
330 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800331 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
332 // careful about updating the config, but there are fewer and fewer logs
333 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800334 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
335 "aos.message_bridge.RemoteMessage");
336 } else {
337 CHECK(HasChannel<RemoteMessage>(channel, node))
338 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
339 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
340 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800341 // Only bother to remap if there's something on the channel. We can
342 // tell if the channel was marked NOT_LOGGED or not. This makes the
343 // config not change un-necesarily when we replay a log with NOT_LOGGED
344 // messages.
345 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
346 RemapLoggedChannel<RemoteMessage>(channel, node);
347 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800348 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700349 }
350 }
351
Austin Schuh6aa77be2020-02-22 21:06:40 -0800352 if (replay_configuration) {
353 CHECK_EQ(configuration::MultiNode(configuration()),
354 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700355 << ": Log file and replay config need to both be multi or single "
356 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800357 }
358
Austin Schuh6f3babe2020-01-26 20:34:50 -0800359 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700360 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800361 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800362 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700363 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800364 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700365 << ": Log file and replay config need to have matching nodes "
366 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700367 for (const Node *node : *logged_configuration()->nodes()) {
368 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700369 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
370 << " in logged config that is not present in the replay "
371 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700372 }
373 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800374 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800375 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800376 }
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600377
378 before_send_callbacks_.resize(configuration()->channels()->size());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800379}
380
Austin Schuh6aa77be2020-02-22 21:06:40 -0800381LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700382 if (event_loop_factory_unique_ptr_) {
383 Deregister();
384 } else if (event_loop_factory_ != nullptr) {
385 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
386 "is destroyed";
387 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700388 // Zero out some buffers. It's easy to do use-after-frees on these, so make
389 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700390 if (remapped_configuration_buffer_) {
391 remapped_configuration_buffer_->Wipe();
392 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800393}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800394
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800395const Configuration *LogReader::logged_configuration() const {
Alexei Strots1f51ac72023-05-15 10:14:54 -0700396 return log_files_.config();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800397}
398
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800399const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800400 return remapped_configuration_;
401}
402
Austin Schuh07676622021-01-21 18:59:17 -0800403std::vector<const Node *> LogReader::LoggedNodes() const {
404 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800405}
Austin Schuh15649d62019-12-28 16:36:38 -0800406
Austin Schuh11d43732020-09-21 17:28:30 -0700407monotonic_clock::time_point LogReader::monotonic_start_time(
408 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800409 State *state =
410 states_[configuration::GetNodeIndex(configuration(), node)].get();
411 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
412
Austin Schuhf665eb42022-02-03 18:26:25 -0800413 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800414}
415
Austin Schuh11d43732020-09-21 17:28:30 -0700416realtime_clock::time_point LogReader::realtime_start_time(
417 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800418 State *state =
419 states_[configuration::GetNodeIndex(configuration(), node)].get();
420 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
421
Austin Schuhf665eb42022-02-03 18:26:25 -0800422 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800423}
424
Austin Schuh58646e22021-08-23 23:51:46 -0700425void LogReader::OnStart(std::function<void()> fn) {
426 CHECK(!configuration::MultiNode(configuration()));
427 OnStart(nullptr, std::move(fn));
428}
429
430void LogReader::OnStart(const Node *node, std::function<void()> fn) {
431 const int node_index = configuration::GetNodeIndex(configuration(), node);
432 CHECK_GE(node_index, 0);
433 CHECK_LT(node_index, static_cast<int>(states_.size()));
434 State *state = states_[node_index].get();
435 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
436
437 state->OnStart(std::move(fn));
438}
439
James Kuszmaula16a7912022-06-17 10:58:12 -0700440void LogReader::State::QueueThreadUntil(BootTimestamp time) {
441 if (threading_ == ThreadedBuffering::kYes) {
442 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
443 message_queuer_.emplace(
444 [this](const BootTimestamp queue_until) {
445 // This will be called whenever anything prompts us for any state
446 // change; there may be wakeups that result in us not having any new
447 // data to push (even if we aren't done), in which case we will return
448 // nullopt but not done().
449 if (last_queued_message_.has_value() &&
450 queue_until < last_queued_message_) {
451 return util::ThreadedQueue<TimestampedMessage,
452 BootTimestamp>::PushResult{
453 std::nullopt, false,
454 last_queued_message_ == BootTimestamp::max_time()};
455 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700456
James Kuszmaula16a7912022-06-17 10:58:12 -0700457 TimestampedMessage *message = timestamp_mapper_->Front();
458 // Upon reaching the end of the log, exit.
459 if (message == nullptr) {
460 last_queued_message_ = BootTimestamp::max_time();
461 return util::ThreadedQueue<TimestampedMessage,
462 BootTimestamp>::PushResult{std::nullopt,
463 false, true};
464 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700465
James Kuszmaula16a7912022-06-17 10:58:12 -0700466 last_queued_message_ = message->monotonic_event_time;
467 const util::ThreadedQueue<TimestampedMessage,
468 BootTimestamp>::PushResult result{
469 *message, queue_until >= last_queued_message_, false};
470 timestamp_mapper_->PopFront();
471 SeedSortedMessages();
472 return result;
473 },
474 time);
475 // Spin until the first few seconds of messages are queued up so that we
476 // don't end up with delays/inconsistent timing during the first few seconds
477 // of replay.
478 message_queuer_->WaitForNoMoreWork();
479 }
480}
481
Austin Schuh58646e22021-08-23 23:51:46 -0700482void LogReader::State::OnStart(std::function<void()> fn) {
483 on_starts_.emplace_back(std::move(fn));
484}
485
486void LogReader::State::RunOnStart() {
487 SetRealtimeOffset(monotonic_start_time(boot_count()),
488 realtime_start_time(boot_count()));
489
Alexei Strots036d84e2023-05-03 16:05:12 -0700490 VLOG(1) << "Starting for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700491 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800492 auto fn = [this]() {
493 for (size_t i = 0; i < on_starts_.size(); ++i) {
494 on_starts_[i]();
495 }
496 };
497 if (event_loop_factory_) {
498 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
499 } else {
500 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700501 }
502 stopped_ = false;
503 started_ = true;
504}
505
506void LogReader::OnEnd(std::function<void()> fn) {
507 CHECK(!configuration::MultiNode(configuration()));
508 OnEnd(nullptr, std::move(fn));
509}
510
511void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
512 const int node_index = configuration::GetNodeIndex(configuration(), node);
513 CHECK_GE(node_index, 0);
514 CHECK_LT(node_index, static_cast<int>(states_.size()));
515 State *state = states_[node_index].get();
516 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
517
518 state->OnEnd(std::move(fn));
519}
520
521void LogReader::State::OnEnd(std::function<void()> fn) {
522 on_ends_.emplace_back(std::move(fn));
523}
524
525void LogReader::State::RunOnEnd() {
Alexei Strots036d84e2023-05-03 16:05:12 -0700526 VLOG(1) << "Ending for node '" << MaybeNodeName(node()) << "' at time "
Austin Schuh58646e22021-08-23 23:51:46 -0700527 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800528 auto fn = [this]() {
529 for (size_t i = 0; i < on_ends_.size(); ++i) {
530 on_ends_[i]();
531 }
532 };
533 if (event_loop_factory_) {
534 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
535 } else {
536 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700537 }
538
539 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800540 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700541 if (message_queuer_.has_value()) {
542 message_queuer_->StopPushing();
543 }
Austin Schuh58646e22021-08-23 23:51:46 -0700544}
545
James Kuszmaul94ca5132022-07-19 09:11:08 -0700546std::vector<
547 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
548LogReader::State::NonExclusiveChannels() {
549 CHECK_NOTNULL(node_event_loop_factory_);
550 const aos::Configuration *config = node_event_loop_factory_->configuration();
551 std::vector<
552 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
553 result{// Timing reports can be sent by logged and replayed applications.
554 {aos::configuration::GetChannel(config, "/aos",
555 "aos.timing.Report", "", node_),
556 NodeEventLoopFactory::ExclusiveSenders::kNo},
557 // AOS_LOG may be used in the log and in replay.
558 {aos::configuration::GetChannel(
559 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
560 NodeEventLoopFactory::ExclusiveSenders::kNo}};
561 for (const Node *const node : configuration::GetNodes(config)) {
562 if (node == nullptr) {
563 break;
564 }
565 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
566 config,
567 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700568 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700569 // The old-style remote timestamp channel can be populated from any
570 // channel, simulated or replayed.
571 if (old_timestamp_channel != nullptr) {
572 result.push_back(std::make_pair(
573 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
574 }
575 }
576 // Remove any channels that weren't found due to not existing in the
577 // config.
578 for (size_t ii = 0; ii < result.size();) {
579 if (result[ii].first == nullptr) {
580 result.erase(result.begin() + ii);
581 } else {
582 ++ii;
583 }
584 }
585 return result;
586}
587
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800588void LogReader::Register() {
589 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800590 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800591 Register(event_loop_factory_unique_ptr_.get());
592}
593
Austin Schuh58646e22021-08-23 23:51:46 -0700594void LogReader::RegisterWithoutStarting(
595 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800596 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700597 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800598 filters_ =
599 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800600 event_loop_factory_->configuration(), logged_configuration(),
Alexei Strots1f51ac72023-05-15 10:14:54 -0700601 log_files_.front_boots(), FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800602 chrono::duration_cast<chrono::nanoseconds>(
603 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800604
Austin Schuhe639ea12021-01-25 13:00:22 -0800605 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700606 for (const Node *node : configuration::GetNodes(configuration())) {
Alexei Strots1f51ac72023-05-15 10:14:54 -0700607 size_t node_index = configuration::GetNodeIndex(configuration(), node);
608 std::string_view node_name = MaybeNodeName(node);
Austin Schuh315b96b2020-12-11 21:21:12 -0800609
James Kuszmaula16a7912022-06-17 10:58:12 -0700610 // We don't run with threading on the buffering for simulated event loops
611 // because we haven't attempted to validate how the interactions beteen the
612 // buffering and the timestamp mapper works when running multiple nodes
613 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800614 states_[node_index] = std::make_unique<State>(
Alexei Strots1f51ac72023-05-15 10:14:54 -0700615 !log_files_.ContainsPartsForNode(node_name)
Austin Schuh287d43d2020-12-04 20:19:33 -0800616 ? nullptr
Alexei Strots1f51ac72023-05-15 10:14:54 -0700617 : std::make_unique<TimestampMapper>(node_name, log_files_),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700618 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600619 State::ThreadedBuffering::kNo, MaybeMakeReplayChannelIndices(node),
620 before_send_callbacks_);
Austin Schuh8bd96322020-02-13 21:18:22 -0800621 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700622 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800623 event_loop_factory_->GetNodeEventLoopFactory(node),
624 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700625
626 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800627 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800628 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800629 filters_->SetTimestampMappers(std::move(timestamp_mappers));
630
631 // Note: this needs to be set before any times are pulled, or we won't observe
632 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800633 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700634
Austin Schuh287d43d2020-12-04 20:19:33 -0800635 for (const Node *node : configuration::GetNodes(configuration())) {
636 const size_t node_index =
637 configuration::GetNodeIndex(configuration(), node);
638 State *state = states_[node_index].get();
639 for (const Node *other_node : configuration::GetNodes(configuration())) {
640 const size_t other_node_index =
641 configuration::GetNodeIndex(configuration(), other_node);
642 State *other_state = states_[other_node_index].get();
643 if (other_state != state) {
644 state->AddPeer(other_state);
645 }
646 }
647 }
648
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700649 // Register after making all the State objects so we can build references
650 // between them.
651 for (const Node *node : configuration::GetNodes(configuration())) {
652 const size_t node_index =
653 configuration::GetNodeIndex(configuration(), node);
654 State *state = states_[node_index].get();
655
Austin Schuh58646e22021-08-23 23:51:46 -0700656 // If we didn't find any log files with data in them, we won't ever get a
657 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700658 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700659 continue;
660 }
Eric Schmiedebergb38477e2022-12-02 16:08:04 -0700661
Austin Schuh58646e22021-08-23 23:51:46 -0700662 ++live_nodes_;
663
664 NodeEventLoopFactory *node_factory =
665 event_loop_factory_->GetNodeEventLoopFactory(node);
666 node_factory->OnStartup([this, state, node]() {
667 RegisterDuringStartup(state->MakeEventLoop(), node);
668 });
669 node_factory->OnShutdown([this, state, node]() {
670 RegisterDuringStartup(nullptr, node);
671 state->DestroyEventLoop();
672 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700673 }
674
James Kuszmaul46d82582020-05-09 19:50:09 -0700675 if (live_nodes_ == 0) {
676 LOG(FATAL)
677 << "Don't have logs from any of the nodes in the replay config--are "
678 "you sure that the replay config matches the original config?";
679 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800680
Austin Schuh87dd3832021-01-01 23:07:31 -0800681 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800682
Austin Schuh858c9f32020-08-31 16:56:12 -0700683 for (std::unique_ptr<State> &state : states_) {
684 state->SeedSortedMessages();
685 }
686
Austin Schuh6f3babe2020-01-26 20:34:50 -0800687 // Forwarding is tracked per channel. If it is enabled, we want to turn it
688 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700689 // nodes, and also replayed on the other nodes. This may not satisfy all
690 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800691 if (configuration::MultiNode(event_loop_factory_->configuration())) {
692 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
693 const Channel *channel = logged_configuration()->channels()->Get(i);
694 const Node *node = configuration::GetNode(
695 configuration(), channel->source_node()->string_view());
696
Austin Schuh8bd96322020-02-13 21:18:22 -0800697 State *state =
698 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800699
700 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700701 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800702
703 event_loop_factory_->DisableForwarding(remapped_channel);
704 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700705
706 // If we are replaying a log, we don't want a bunch of redundant messages
707 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700708 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800709 }
Austin Schuh891214d2021-11-11 20:35:02 -0800710
711 // Write pseudo start times out to file now that we are all setup.
712 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700713}
714
715void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
716 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800717 StartAfterRegister(event_loop_factory);
718}
719
720void LogReader::StartAfterRegister(
721 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700722 // We want to start the log file at the last start time of the log files
723 // from all the nodes. Compute how long each node's simulation needs to run
724 // to move time to this point.
725 distributed_clock::time_point start_time = distributed_clock::min_time;
726
727 // TODO(austin): We want an "OnStart" callback for each node rather than
728 // running until the last node.
729
730 for (std::unique_ptr<State> &state : states_) {
Alexei Strotsb8c3a702023-04-19 21:38:25 -0700731 CHECK(state);
Austin Schuh58646e22021-08-23 23:51:46 -0700732 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700733 << " for node '" << MaybeNodeName(state->node()) << "' now "
Austin Schuh58646e22021-08-23 23:51:46 -0700734 << state->monotonic_now();
735 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
736 continue;
737 }
738 // And start computing the start time on the distributed clock now that
739 // that works.
740 start_time = std::max(
741 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
742 }
743
744 // TODO(austin): If a node doesn't have a start time, we might not queue
745 // enough. If this happens, we'll explode with a frozen error eventually.
746
747 CHECK_GE(start_time, distributed_clock::epoch())
748 << ": Hmm, we have a node starting before the start of time. Offset "
749 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800750
Austin Schuhdda74ec2021-01-03 19:30:37 -0800751 {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800752 VLOG(1) << "Running until " << start_time << " in Register";
753 event_loop_factory_->RunFor(start_time.time_since_epoch());
754 VLOG(1) << "At start time";
Austin Schuhdda74ec2021-01-03 19:30:37 -0800755 }
Austin Schuh92547522019-12-28 14:33:43 -0800756
Austin Schuh8bd96322020-02-13 21:18:22 -0800757 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700758 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700759 if (state->realtime_start_time(0) != realtime_clock::min_time) {
760 state->SetRealtimeOffset(state->monotonic_start_time(0),
761 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700762 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700763 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
Alexei Strots036d84e2023-05-03 16:05:12 -0700764 << " for node '" << MaybeNodeName(state->event_loop()->node())
765 << "' now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700766 }
767
768 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800769 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800770 }
771}
772
Austin Schuh2f8fd752020-09-01 22:38:28 -0700773message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800774 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800775 if (filters_) {
776 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800777 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800778 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800779}
780
James Kuszmaul09632422022-05-25 15:56:19 -0700781// TODO(jkuszmaul): Make in-line modifications to
782// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
783// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800784void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700785 filters_ =
786 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
787 event_loop->configuration(), logged_configuration(),
Alexei Strots1f51ac72023-05-15 10:14:54 -0700788 log_files_.front_boots(), FLAGS_skip_order_validation,
James Kuszmaul09632422022-05-25 15:56:19 -0700789 chrono::duration_cast<chrono::nanoseconds>(
790 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
791
792 std::vector<TimestampMapper *> timestamp_mappers;
793 for (const Node *node : configuration::GetNodes(configuration())) {
Alexei Strots1f51ac72023-05-15 10:14:54 -0700794 auto node_name = MaybeNodeName(node);
James Kuszmaul09632422022-05-25 15:56:19 -0700795 const size_t node_index =
796 configuration::GetNodeIndex(configuration(), node);
James Kuszmaul09632422022-05-25 15:56:19 -0700797
798 states_[node_index] = std::make_unique<State>(
Alexei Strots1f51ac72023-05-15 10:14:54 -0700799 !log_files_.ContainsPartsForNode(node_name)
James Kuszmaul09632422022-05-25 15:56:19 -0700800 ? nullptr
Alexei Strots1f51ac72023-05-15 10:14:54 -0700801 : std::make_unique<TimestampMapper>(node_name, log_files_),
James Kuszmaulb11a1502022-07-01 16:02:25 -0700802 filters_.get(), std::bind(&LogReader::NoticeRealtimeEnd, this), node,
Eric Schmiedebergae00e732023-04-12 15:53:17 -0600803 State::ThreadedBuffering::kYes, MaybeMakeReplayChannelIndices(node),
804 before_send_callbacks_);
James Kuszmaul09632422022-05-25 15:56:19 -0700805 State *state = states_[node_index].get();
806
807 state->SetChannelCount(logged_configuration()->channels()->size());
808 timestamp_mappers.emplace_back(state->timestamp_mapper());
809 }
810
811 filters_->SetTimestampMappers(std::move(timestamp_mappers));
812
813 for (const Node *node : configuration::GetNodes(configuration())) {
814 const size_t node_index =
815 configuration::GetNodeIndex(configuration(), node);
816 State *state = states_[node_index].get();
817 for (const Node *other_node : configuration::GetNodes(configuration())) {
818 const size_t other_node_index =
819 configuration::GetNodeIndex(configuration(), other_node);
820 State *other_state = states_[other_node_index].get();
821 if (other_state != state) {
822 state->AddPeer(other_state);
823 }
824 }
825 }
826 for (const Node *node : configuration::GetNodes(configuration())) {
827 if (node == nullptr || node->name()->string_view() ==
828 event_loop->node()->name()->string_view()) {
829 Register(event_loop, event_loop->node());
830 } else {
831 Register(nullptr, node);
832 }
833 }
Austin Schuh58646e22021-08-23 23:51:46 -0700834}
835
836void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800837 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700838 states_[configuration::GetNodeIndex(configuration(), node)].get();
839
840 // If we didn't find any log files with data in them, we won't ever get a
841 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700842 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700843 return;
844 }
James Kuszmaul09632422022-05-25 15:56:19 -0700845
846 if (event_loop != nullptr) {
847 ++live_nodes_;
848 }
Austin Schuh58646e22021-08-23 23:51:46 -0700849
850 if (event_loop_factory_ != nullptr) {
851 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
852 [this, event_loop, node]() {
853 RegisterDuringStartup(event_loop, node);
854 });
855 } else {
856 RegisterDuringStartup(event_loop, node);
857 }
858}
859
860void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700861 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700862 CHECK(event_loop->configuration() == configuration());
863 }
864
865 State *state =
866 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800867
James Kuszmaul09632422022-05-25 15:56:19 -0700868 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800869 state->ClearTimeFlags();
870 }
871
Austin Schuh858c9f32020-08-31 16:56:12 -0700872 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800873
Tyler Chatow67ddb032020-01-12 14:30:04 -0800874 // We don't run timing reports when trying to print out logged data, because
875 // otherwise we would end up printing out the timing reports themselves...
876 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700877 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700878 event_loop->SkipTimingReport();
879 event_loop->SkipAosLog();
880 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800881
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700882 for (size_t logged_channel_index = 0;
883 logged_channel_index < logged_configuration()->channels()->size();
884 ++logged_channel_index) {
885 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700886 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700887 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800888
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700889 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700890 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700891
892 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700893
Austin Schuh58646e22021-08-23 23:51:46 -0700894 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
895 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700896 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700897 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800898
Austin Schuh58646e22021-08-23 23:51:46 -0700899 // We've got a message which is being forwarded to this node.
900 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700901
902 source_state =
903 states_[configuration::GetNodeIndex(configuration(), source_node)]
904 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800905 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700906
Austin Schuh58646e22021-08-23 23:51:46 -0700907 // We are the source, and it is forwarded.
908 const bool is_forwarded =
909 configuration::ChannelIsSendableOnNode(channel, node) &&
910 configuration::ConnectionCount(channel);
911
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700912 state->SetChannel(
913 logged_channel_index,
914 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700915 event_loop && logged &&
916 configuration::ChannelIsReadableOnNode(channel, node)
917 ? event_loop->MakeRawSender(channel)
918 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700919 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700920
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700921 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700922 const Node *source_node = configuration::GetNode(
923 configuration(), channel->source_node()->string_view());
924
925 for (const Connection *connection : *channel->destination_nodes()) {
926 const bool delivery_time_is_logged =
927 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
928 source_node);
929
930 if (delivery_time_is_logged) {
931 State *destination_state =
932 states_[configuration::GetNodeIndex(
933 configuration(), connection->name()->string_view())]
934 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700935 if (destination_state) {
936 destination_state->SetRemoteTimestampSender(
937 logged_channel_index,
938 event_loop ? state->RemoteTimestampSender(channel, connection)
939 : nullptr);
940 }
Austin Schuh58646e22021-08-23 23:51:46 -0700941 }
942 }
943 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800944 }
945
Austin Schuh58646e22021-08-23 23:51:46 -0700946 if (!event_loop) {
947 state->ClearRemoteTimestampSenders();
948 state->set_timer_handler(nullptr);
949 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800950 return;
951 }
952
Austin Schuh858c9f32020-08-31 16:56:12 -0700953 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700954 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800955 --live_nodes_;
Alexei Strots036d84e2023-05-03 16:05:12 -0700956 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
957 << "' down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700958 if (exit_on_finish_ && live_nodes_ == 0 &&
959 event_loop_factory_ != nullptr) {
James Kuszmaulb11a1502022-07-01 16:02:25 -0700960 event_loop_factory_->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800961 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800962 return;
963 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700964
Austin Schuhdda74ec2021-01-03 19:30:37 -0800965 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700966
967 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
968 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800969
Austin Schuhe309d2a2019-11-29 13:25:21 -0800970 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700971 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700972 if (event_loop_factory_ != nullptr) {
973 // Only enforce exact timing in simulation.
974 if (!FLAGS_skip_order_validation) {
975 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
976 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
977 << monotonic_now << " trying to send "
978 << timestamped_message.monotonic_event_time << " failure "
979 << state->DebugString();
980 } else if (BootTimestamp{.boot = state->boot_count(),
981 .time = monotonic_now} !=
982 timestamped_message.monotonic_event_time) {
983 LOG(WARNING) << "Check failed: monotonic_now == "
984 "timestamped_message.monotonic_event_time) ("
985 << monotonic_now << " vs. "
986 << timestamped_message.monotonic_event_time
987 << "): " << FlatbufferToJson(state->event_loop()->node())
988 << " Now " << monotonic_now << " trying to send "
989 << timestamped_message.monotonic_event_time << " failure "
990 << state->DebugString();
991 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700992 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800993
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700994 if (timestamped_message.monotonic_event_time.time >
995 state->monotonic_start_time(
996 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700997 event_loop_factory_ != nullptr ||
998 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800999 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001000 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -07001001 BootTimestamp::min_time() &&
1002 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001003 // Confirm that the message was sent on the sending node before the
1004 // destination node (this node). As a proxy, do this by making sure
1005 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001006 //
1007 // TODO(austin): <= means that the cause message (which we know) could
1008 // happen after the effect even though we know they are at the same
1009 // time. I doubt anyone will notice for a bit, but we should really
1010 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001011 BootTimestamp monotonic_remote_now =
1012 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001013 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001014 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001015 monotonic_remote_now.boot)
1016 << state->event_loop()->node()->name()->string_view() << " to "
1017 << state->remote_node(timestamped_message.channel_index)
1018 ->name()
1019 ->string_view()
1020 << " while trying to send a message on "
1021 << configuration::CleanedChannelToString(
1022 logged_configuration()->channels()->Get(
1023 timestamped_message.channel_index))
1024 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001025 CHECK_LE(timestamped_message.monotonic_remote_time,
1026 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001027 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001028 << state->remote_node(timestamped_message.channel_index)
1029 ->name()
1030 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001031 << " while trying to send a message on "
1032 << configuration::CleanedChannelToString(
1033 logged_configuration()->channels()->Get(
1034 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001035 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001036 } else if (monotonic_remote_now.boot !=
1037 timestamped_message.monotonic_remote_time.boot) {
1038 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1039 << " vs "
1040 << timestamped_message.monotonic_remote_time.boot;
1041 } else if (timestamped_message.monotonic_remote_time >
1042 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001043 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001044 << "Check failed: timestamped_message.monotonic_remote_time < "
1045 "state->monotonic_remote_now(timestamped_message.channel_"
1046 "index) ("
1047 << timestamped_message.monotonic_remote_time << " vs. "
1048 << state->monotonic_remote_now(
1049 timestamped_message.channel_index)
1050 << ") " << state->event_loop()->node()->name()->string_view()
1051 << " to "
1052 << state->remote_node(timestamped_message.channel_index)
1053 ->name()
1054 ->string_view()
1055 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001056 << " ("
1057 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001058 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001059 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001060 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001061 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001062 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001063 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 << ") " << state->DebugString();
1065 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001066 }
1067
Austin Schuh15649d62019-12-28 16:36:38 -08001068 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001069 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001070 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001071
Alexei Strots036d84e2023-05-03 16:05:12 -07001072 VLOG(1) << "For node '" << MaybeNodeName(state->event_loop()->node())
1073 << "' sending at " << timestamped_message.monotonic_event_time
1074 << " : " << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001075 // TODO(austin): std::move channel_data in and make that efficient in
1076 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001077 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001078 } else if (state->found_last_message() ||
1079 (!ignore_missing_data_ &&
1080 // When starting up, we can have data which was sent before
1081 // the log starts, but the timestamp was after the log
1082 // starts. This is unreasonable to avoid, so ignore the
1083 // missing data.
1084 timestamped_message.monotonic_remote_time.time >=
1085 state->monotonic_remote_start_time(
1086 timestamped_message.monotonic_remote_time.boot,
1087 timestamped_message.channel_index) &&
1088 !FLAGS_skip_missing_forwarding_entries)) {
1089 if (!state->found_last_message()) {
1090 // We've found a timestamp without data that we expect to have data
1091 // for. This likely means that we are at the end of the log file.
1092 // Record it and CHECK that in the rest of the log file, we don't find
1093 // any more data on that channel. Not all channels will end at the
1094 // same point in time since they can be in different files.
1095 VLOG(1) << "Found the last message on channel "
1096 << timestamped_message.channel_index << ", "
1097 << configuration::CleanedChannelToString(
1098 logged_configuration()->channels()->Get(
1099 timestamped_message.channel_index))
Alexei Strots036d84e2023-05-03 16:05:12 -07001100 << " on node '" << MaybeNodeName(state->event_loop()->node())
1101 << "' at " << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001102
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001103 // The user might be working with log files from 1 node but forgot to
1104 // configure the infrastructure to log data for a remote channel on
1105 // that node. That can be very hard to debug, even though the log
1106 // reader is doing the right thing. At least log a warning in that
1107 // case and tell the user what is happening so they can either update
1108 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001109 const std::vector<std::string> logger_nodes =
Alexei Strots1f51ac72023-05-15 10:14:54 -07001110 log_files_.logger_nodes();
1111 if (!logger_nodes.empty()) {
Austin Schuh2bb80e02021-03-20 21:46:17 -07001112 // We have old logs which don't have the logger nodes logged. In
1113 // that case, we can't be helpful :(
1114 bool data_logged = false;
1115 const Channel *channel = logged_configuration()->channels()->Get(
1116 timestamped_message.channel_index);
1117 for (const std::string &node : logger_nodes) {
1118 data_logged |=
1119 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1120 }
1121 if (!data_logged) {
1122 LOG(WARNING) << "Got a timestamp without any logfiles which "
1123 "could contain data for channel "
1124 << configuration::CleanedChannelToString(channel);
1125 LOG(WARNING) << "Only have logs logged on ["
1126 << absl::StrJoin(logger_nodes, ", ") << "]";
1127 LOG(WARNING)
1128 << "Dropping the rest of the data on "
1129 << state->event_loop()->node()->name()->string_view();
1130 LOG(WARNING)
1131 << "Consider using --skip_missing_forwarding_entries to "
1132 "bypass this, update your config to log it, or add data "
1133 "from one of the nodes it is logged on.";
1134 }
1135 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001136 // Now that we found the end of one channel, artificially stop the
1137 // rest by setting the found_last_message bit. It is confusing when
1138 // part of your data gets replayed but not all. The rest of them will
1139 // get dropped as they are replayed to keep memory usage down.
1140 state->SetFoundLastMessage(true);
1141
1142 // Vector storing if we've seen a nullptr message or not per channel.
1143 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001144 }
1145
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001146 // Make sure that once we have seen the last message on a channel,
1147 // data doesn't start back up again. If the user wants to play
1148 // through events like this, they can set
1149 // --skip_missing_forwarding_entries or ignore_missing_data_.
1150 if (timestamped_message.data == nullptr) {
1151 state->set_last_message(timestamped_message.channel_index);
1152 } else {
1153 if (state->last_message(timestamped_message.channel_index)) {
1154 LOG(FATAL) << "Found missing data in the middle of the log file on "
1155 "channel "
1156 << timestamped_message.channel_index << " "
1157 << configuration::StrippedChannelToString(
1158 logged_configuration()->channels()->Get(
1159 timestamped_message.channel_index))
1160 << " " << timestamped_message << " "
1161 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001162 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001163 }
Austin Schuh92547522019-12-28 14:33:43 -08001164 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001165 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001166 LOG(WARNING)
1167 << "Not sending data from before the start of the log file. "
1168 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1169 .count()
1170 << " start "
1171 << monotonic_start_time(state->node()).time_since_epoch().count()
1172 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001173 }
1174
James Kuszmaula16a7912022-06-17 10:58:12 -07001175 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001176 if (next_time != BootTimestamp::max_time()) {
1177 if (next_time.boot != state->boot_count()) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001178 VLOG(1) << "Next message for node '"
Austin Schuh58646e22021-08-23 23:51:46 -07001179 << MaybeNodeName(state->event_loop()->node())
Alexei Strots036d84e2023-05-03 16:05:12 -07001180 << "' is on the next boot, " << next_time << " now is "
Austin Schuh58646e22021-08-23 23:51:46 -07001181 << state->monotonic_now();
1182 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001183 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001184 return;
1185 }
James Kuszmaul09632422022-05-25 15:56:19 -07001186 if (event_loop_factory_ != nullptr) {
Alexei Strots036d84e2023-05-03 16:05:12 -07001187 VLOG(1) << "Scheduling for node '"
1188 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1189 << next_time.time << "("
James Kuszmaul09632422022-05-25 15:56:19 -07001190 << state->ToDistributedClock(next_time.time)
1191 << " distributed), now is " << state->monotonic_now();
1192 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001193 VLOG(1) << "Scheduling for node '"
1194 << MaybeNodeName(state->event_loop()->node()) << "' wakeup for "
1195 << next_time.time << ", now is " << state->monotonic_now();
James Kuszmaul09632422022-05-25 15:56:19 -07001196 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001197 // TODO(james): This can result in negative times getting passed-through
1198 // in realtime replay.
Philipp Schradera6712522023-07-05 20:25:11 -07001199 state->Schedule(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001200 } else {
Alexei Strots036d84e2023-05-03 16:05:12 -07001201 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1202 << "': No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001203 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001204 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001205 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001206 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001207 // Doesn't apply to single-EventLoop replay since the watchers in question
1208 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001209 if (event_loop_factory_ != nullptr) {
Philipp Schradera6712522023-07-05 20:25:11 -07001210 state->Schedule(monotonic_now + event_loop_factory_->send_delay() +
1211 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001212 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001213 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001214
Alexei Strots036d84e2023-05-03 16:05:12 -07001215 VLOG(1) << "Node '" << MaybeNodeName(state->event_loop()->node())
1216 << "': Done sending at "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001217 << state->event_loop()->context().monotonic_event_time << " now "
1218 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001219 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001220
James Kuszmaula16a7912022-06-17 10:58:12 -07001221 state->SeedSortedMessages();
1222
1223 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001224 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001225 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1226 if (start_time_ != realtime_clock::min_time) {
1227 state->SetStartTimeFlag(start_time_);
1228 }
1229 if (end_time_ != realtime_clock::max_time) {
1230 state->SetEndTimeFlag(end_time_);
James Kuszmaulb11a1502022-07-01 16:02:25 -07001231 ++live_nodes_with_realtime_time_end_;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001232 }
Austin Schuh58646e22021-08-23 23:51:46 -07001233 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001234 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001235 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001236 // Queue up messages and then set clock offsets (we don't want to set
1237 // clock offsets before we've done the work of getting the first messages
1238 // primed).
1239 state->QueueThreadUntil(
1240 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1241 std::chrono::duration<double>(
1242 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001243 state->MaybeSetClockOffset();
Philipp Schradera6712522023-07-05 20:25:11 -07001244 state->Schedule(next_time.time);
1245 state->SetUpStartupTimer();
Austin Schuh58646e22021-08-23 23:51:46 -07001246 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001247 }
1248}
1249
Austin Schuhe33c08d2022-02-03 18:15:21 -08001250void LogReader::SetEndTime(std::string end_time) {
1251 if (end_time.empty()) {
1252 SetEndTime(realtime_clock::max_time);
1253 } else {
1254 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1255 aos::realtime_clock::FromString(end_time);
1256 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1257 << "'. Expected a date in the format of "
1258 "2021-01-15_15-30-35.000000000.";
1259 SetEndTime(*parsed_end_time);
1260 }
1261}
1262
1263void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1264 end_time_ = end_time;
1265}
1266
1267void LogReader::SetStartTime(std::string start_time) {
1268 if (start_time.empty()) {
1269 SetStartTime(realtime_clock::min_time);
1270 } else {
1271 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1272 aos::realtime_clock::FromString(start_time);
1273 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1274 << "'. Expected a date in the format of "
1275 "2021-01-15_15-30-35.000000000.";
1276 SetStartTime(*parsed_start_time);
1277 }
1278}
1279
1280void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1281 start_time_ = start_time;
1282}
1283
Austin Schuhe309d2a2019-11-29 13:25:21 -08001284void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001285 // Make sure that things get destroyed in the correct order, rather than
1286 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001287 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001288 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001289 }
Austin Schuh92547522019-12-28 14:33:43 -08001290
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001291 event_loop_factory_unique_ptr_.reset();
1292 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001293}
1294
James Kuszmaul53da7f32022-09-11 11:11:55 -07001295namespace {
1296// Checks if the specified channel name/type exists in the config and, depending
1297// on the value of conflict_handling, calls conflict_handler or just dies.
1298template <typename F>
1299void CheckAndHandleRemapConflict(std::string_view new_name,
1300 std::string_view new_type,
1301 const Configuration *config,
1302 LogReader::RemapConflict conflict_handling,
1303 F conflict_handler) {
1304 const Channel *existing_channel =
1305 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1306 if (existing_channel != nullptr) {
1307 switch (conflict_handling) {
1308 case LogReader::RemapConflict::kDisallow:
1309 LOG(FATAL)
1310 << "Channel "
1311 << configuration::StrippedChannelToString(existing_channel)
1312 << " is already used--you can't remap a logged channel to it.";
1313 break;
1314 case LogReader::RemapConflict::kCascade:
1315 LOG(INFO) << "Automatically remapping "
1316 << configuration::StrippedChannelToString(existing_channel)
1317 << " to avoid conflicts.";
1318 conflict_handler();
1319 break;
1320 }
1321 }
1322}
1323} // namespace
1324
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001325void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001326 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001327 std::string_view new_type,
1328 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001329 RemapLoggedChannel(name, type, nullptr, add_prefix, new_type,
1330 conflict_handling);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001331}
1332
Austin Schuh01b4c352020-09-21 23:09:39 -07001333void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1334 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001335 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001336 std::string_view new_type,
1337 RemapConflict conflict_handling) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001338 if (node != nullptr) {
1339 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1340 }
1341 if (replay_channels_ != nullptr) {
1342 CHECK(std::find(replay_channels_->begin(), replay_channels_->end(),
1343 std::make_pair(std::string{name}, std::string{type})) !=
1344 replay_channels_->end())
1345 << "Attempted to remap channel " << name << " " << type
1346 << " which is not included in the replay channels passed to LogReader.";
1347 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001348 const Channel *remapped_channel =
1349 configuration::GetChannel(logged_configuration(), name, type, "", node);
1350 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1351 << "\", \"type\": \"" << type << "\"}";
1352 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1353 << "\"}";
1354 VLOG(1) << "Remapped "
1355 << aos::configuration::StrippedChannelToString(remapped_channel);
1356
1357 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1358 // we want it to degrade if the heuristics fail to just work.
1359 //
1360 // The easiest way to do this is going to be incredibly specific and verbose.
1361 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1362 // /original/0/spray. Then, create a map from /original/spray to
1363 // /original/0/spray for just the type we were asked for.
1364 if (name != remapped_channel->name()->string_view()) {
1365 MapT new_map;
1366 new_map.match = std::make_unique<ChannelT>();
1367 new_map.match->name = absl::StrCat(add_prefix, name);
1368 new_map.match->type = type;
1369 if (node != nullptr) {
1370 new_map.match->source_node = node->name()->str();
1371 }
1372 new_map.rename = std::make_unique<ChannelT>();
1373 new_map.rename->name =
1374 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1375 maps_.emplace_back(std::move(new_map));
1376 }
1377
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001378 // Then remap the logged channel to the prefixed channel.
Austin Schuh01b4c352020-09-21 23:09:39 -07001379 const size_t channel_index =
1380 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1381 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1382 << "Already remapped channel "
1383 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001384
1385 RemappedChannel remapped_channel_struct;
1386 remapped_channel_struct.remapped_name =
1387 std::string(add_prefix) +
1388 std::string(remapped_channel->name()->string_view());
1389 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001390 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1391 CheckAndHandleRemapConflict(
1392 remapped_channel_struct.remapped_name, remapped_type,
1393 remapped_configuration_, conflict_handling,
1394 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1395 conflict_handling]() {
1396 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1397 node, add_prefix, "", conflict_handling);
1398 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001399 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001400 MakeRemappedConfig();
1401}
1402
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001403void LogReader::RenameLoggedChannel(const std::string_view name,
1404 const std::string_view type,
1405 const std::string_view new_name,
1406 const std::vector<MapT> &add_maps) {
1407 RenameLoggedChannel(name, type, nullptr, new_name, add_maps);
1408}
1409
1410void LogReader::RenameLoggedChannel(const std::string_view name,
1411 const std::string_view type,
1412 const Node *const node,
1413 const std::string_view new_name,
1414 const std::vector<MapT> &add_maps) {
1415 if (node != nullptr) {
1416 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1417 }
1418 // First find the channel and rename it.
1419 const Channel *remapped_channel =
1420 configuration::GetChannel(logged_configuration(), name, type, "", node);
1421 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1422 << "\", \"type\": \"" << type << "\"}";
1423 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1424 << "\"}";
1425 VLOG(1) << "Remapped "
1426 << aos::configuration::StrippedChannelToString(remapped_channel);
1427
1428 const size_t channel_index =
1429 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1430 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1431 << "Already remapped channel "
1432 << configuration::CleanedChannelToString(remapped_channel);
1433
1434 RemappedChannel remapped_channel_struct;
1435 remapped_channel_struct.remapped_name = new_name;
1436 remapped_channel_struct.new_type.clear();
1437 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
1438
1439 // Then add any provided maps.
1440 for (const MapT &map : add_maps) {
1441 maps_.push_back(map);
1442 }
1443
1444 // Finally rewrite the config.
1445 MakeRemappedConfig();
1446}
1447
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001448void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001449 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001450 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001451 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001452 << ": Can't change the mapping after the events are scheduled.";
1453 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001454 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001455
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001456 // If no remapping occurred and we are using the original config, then there
1457 // is nothing interesting to do here.
1458 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001459 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001460 return;
1461 }
1462 // Config to copy Channel definitions from. Use the specified
1463 // replay_configuration_ if it has been provided.
1464 const Configuration *const base_config = replay_configuration_ == nullptr
1465 ? logged_configuration()
1466 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001467
1468 // Create a config with all the channels, but un-sorted/merged. Collect up
1469 // the schemas while we do this. Call MergeConfiguration to sort everything,
1470 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001471
1472 // This is the builder that we use for the config containing all the new
1473 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001474 flatbuffers::FlatBufferBuilder fbb;
1475 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001476 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001477
1478 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1479 << ": Merging logic needs to be updated when the number of channel "
1480 "fields changes.";
1481
1482 // List of schemas.
1483 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1484 // Make sure our new RemoteMessage schema is in there for old logs without it.
1485 schema_map.insert(std::make_pair(
1486 RemoteMessage::GetFullyQualifiedName(),
1487 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1488 message_bridge::RemoteMessageSchema()))));
1489
1490 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001491 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001492 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001493 base_config, logged_configuration()->channels()->Get(pair.first), "",
1494 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001495 channel_offsets.emplace_back(
1496 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001497
1498 if (c->has_destination_nodes()) {
1499 for (const Connection *connection : *c->destination_nodes()) {
1500 switch (connection->timestamp_logger()) {
1501 case LoggerConfig::LOCAL_LOGGER:
1502 case LoggerConfig::NOT_LOGGED:
1503 // There is no timestamp channel associated with this, so ignore it.
1504 break;
1505
1506 case LoggerConfig::REMOTE_LOGGER:
1507 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1508 // We want to make a split timestamp channel regardless of what type
1509 // of log this used to be. No sense propagating the single
1510 // timestamp channel.
1511
1512 CHECK(connection->has_timestamp_logger_nodes());
1513 for (const flatbuffers::String *timestamp_logger_node :
1514 *connection->timestamp_logger_nodes()) {
1515 const Node *node = configuration::GetNode(
1516 logged_configuration(), timestamp_logger_node->string_view());
1517 message_bridge::ChannelTimestampFinder finder(
1518 logged_configuration(), "log_reader", node);
1519
1520 // We are assuming here that all the maps are setup correctly to
1521 // handle arbitrary timestamps. Apply the maps for this node to
1522 // see what name this ends up with.
1523 std::string name = finder.SplitChannelName(
1524 pair.second.remapped_name, c->type()->str(), connection);
1525 std::string unmapped_name = name;
1526 configuration::HandleMaps(logged_configuration()->maps(), &name,
1527 "aos.message_bridge.RemoteMessage",
1528 node);
1529 CHECK_NE(name, unmapped_name)
1530 << ": Remote timestamp channel was not remapped, this is "
1531 "very fishy";
1532 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1533 fbb.CreateString(name);
1534 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1535 fbb.CreateString("aos.message_bridge.RemoteMessage");
1536 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1537 fbb.CreateString(timestamp_logger_node->string_view());
1538
1539 // Now, build a channel. Don't log it, 2 senders, and match the
1540 // source frequency.
1541 Channel::Builder channel_builder(fbb);
1542 channel_builder.add_name(channel_name_offset);
1543 channel_builder.add_type(channel_type_offset);
1544 channel_builder.add_source_node(source_node_offset);
1545 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1546 channel_builder.add_num_senders(2);
1547 if (c->has_frequency()) {
1548 channel_builder.add_frequency(c->frequency());
1549 }
1550 channel_offsets.emplace_back(channel_builder.Finish());
1551 }
1552 break;
1553 }
1554 }
1555 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001556 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001557
Austin Schuh0de30f32020-12-06 12:44:28 -08001558 // Now reconstruct the original channels, translating types as needed
1559 for (const Channel *c : *base_config->channels()) {
1560 // Search for a mapping channel.
1561 std::string_view new_type = "";
1562 for (auto &pair : remapped_channels_) {
1563 const Channel *const remapped_channel =
1564 logged_configuration()->channels()->Get(pair.first);
1565 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1566 remapped_channel->type()->string_view() == c->type()->string_view()) {
1567 new_type = pair.second.new_type;
1568 break;
1569 }
1570 }
1571
1572 // Copy everything over.
1573 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1574
1575 // Add the schema if it doesn't exist.
1576 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1577 CHECK(c->has_schema());
1578 schema_map.insert(std::make_pair(c->type()->string_view(),
1579 RecursiveCopyFlatBuffer(c->schema())));
1580 }
1581 }
1582
1583 // The MergeConfiguration API takes a vector, not a map. Convert.
1584 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1585 while (!schema_map.empty()) {
1586 schemas.emplace_back(std::move(schema_map.begin()->second));
1587 schema_map.erase(schema_map.begin());
1588 }
1589
1590 // Create the Configuration containing the new channels that we want to add.
1591 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1592 channels_offset =
1593 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1594
1595 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001596 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001597 if (base_config->maps()) {
1598 for (const Map *map : *base_config->maps()) {
1599 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1600 }
1601 }
1602
1603 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001604 for (const MapT &map : maps_) {
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001605 CHECK(!map.match->name.empty());
Austin Schuh01b4c352020-09-21 23:09:39 -07001606 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001607 fbb.CreateString(map.match->name);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001608 flatbuffers::Offset<flatbuffers::String> match_type_offset;
1609 if (!map.match->type.empty()) {
1610 match_type_offset = fbb.CreateString(map.match->type);
1611 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001612 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1613 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001614 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001615 }
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001616 CHECK(!map.rename->name.empty());
1617 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1618 fbb.CreateString(map.rename->name);
Austin Schuh0de30f32020-12-06 12:44:28 -08001619 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001620 match_builder.add_name(match_name_offset);
Sanjay Narayanan5ec00232022-07-08 15:21:30 -07001621 if (!match_type_offset.IsNull()) {
1622 match_builder.add_type(match_type_offset);
1623 }
1624 if (!match_source_node_offset.IsNull()) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001625 match_builder.add_source_node(match_source_node_offset);
1626 }
1627 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1628
Austin Schuh0de30f32020-12-06 12:44:28 -08001629 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001630 rename_builder.add_name(rename_name_offset);
1631 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1632
Austin Schuh0de30f32020-12-06 12:44:28 -08001633 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001634 map_builder.add_match(match_offset);
1635 map_builder.add_rename(rename_offset);
1636 map_offsets.emplace_back(map_builder.Finish());
1637 }
1638
Austin Schuh0de30f32020-12-06 12:44:28 -08001639 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1640 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001641
Austin Schuh0de30f32020-12-06 12:44:28 -08001642 // And copy everything else over.
1643 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1644 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1645
1646 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1647 applications_offset =
1648 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1649
1650 // Now insert everything else in unmodified.
1651 ConfigurationBuilder configuration_builder(fbb);
1652 if (!channels_offset.IsNull()) {
1653 configuration_builder.add_channels(channels_offset);
1654 }
1655 if (!maps_offsets.IsNull()) {
1656 configuration_builder.add_maps(maps_offsets);
1657 }
1658 if (!nodes_offset.IsNull()) {
1659 configuration_builder.add_nodes(nodes_offset);
1660 }
1661 if (!applications_offset.IsNull()) {
1662 configuration_builder.add_applications(applications_offset);
1663 }
1664
1665 if (base_config->has_channel_storage_duration()) {
1666 configuration_builder.add_channel_storage_duration(
1667 base_config->channel_storage_duration());
1668 }
1669
1670 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1671 << ": Merging logic needs to be updated when the number of configuration "
1672 "fields changes.";
1673
1674 fbb.Finish(configuration_builder.Finish());
1675
1676 // Clean it up and return it! By using MergeConfiguration here, we'll
1677 // actually get a deduplicated config for free too.
1678 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1679 configuration::MergeConfiguration(
1680 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1681
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001682 remapped_configuration_buffer_ =
1683 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001684 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001685
1686 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001687
1688 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001689}
1690
Naman Guptacf6d4422023-03-01 11:41:00 -08001691std::unique_ptr<const ReplayChannelIndices>
1692LogReader::MaybeMakeReplayChannelIndices(const Node *node) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001693 if (replay_channels_ == nullptr) {
1694 return nullptr;
1695 } else {
Naman Guptacf6d4422023-03-01 11:41:00 -08001696 std::unique_ptr<ReplayChannelIndices> replay_channel_indices =
1697 std::make_unique<ReplayChannelIndices>();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001698 for (auto const &channel : *replay_channels_) {
1699 const Channel *ch = configuration::GetChannel(
1700 logged_configuration(), channel.first, channel.second, "", node);
1701 if (ch == nullptr) {
1702 LOG(WARNING) << "Channel: " << channel.first << " " << channel.second
1703 << " not found in configuration for node: "
1704 << node->name()->string_view() << " Skipping ...";
1705 continue;
1706 }
1707 const size_t channel_index =
1708 configuration::ChannelIndex(logged_configuration(), ch);
Naman Guptacf6d4422023-03-01 11:41:00 -08001709 replay_channel_indices->emplace_back(channel_index);
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001710 }
Naman Guptacf6d4422023-03-01 11:41:00 -08001711 std::sort(replay_channel_indices->begin(), replay_channel_indices->end());
1712 return replay_channel_indices;
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001713 }
1714}
1715
Austin Schuh1c227352021-09-17 12:53:54 -07001716std::vector<const Channel *> LogReader::RemappedChannels() const {
1717 std::vector<const Channel *> result;
1718 result.reserve(remapped_channels_.size());
1719 for (auto &pair : remapped_channels_) {
1720 const Channel *const logged_channel =
1721 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1722
1723 auto channel_iterator = std::lower_bound(
1724 remapped_configuration_->channels()->cbegin(),
1725 remapped_configuration_->channels()->cend(),
1726 std::make_pair(std::string_view(pair.second.remapped_name),
1727 logged_channel->type()->string_view()),
1728 CompareChannels);
1729
1730 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1731 CHECK(EqualsChannels(
1732 *channel_iterator,
1733 std::make_pair(std::string_view(pair.second.remapped_name),
1734 logged_channel->type()->string_view())));
1735 result.push_back(*channel_iterator);
1736 }
1737 return result;
1738}
1739
Austin Schuh6f3babe2020-01-26 20:34:50 -08001740const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001741 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001742 const Channel *channel) {
1743 std::string_view channel_name = channel->name()->string_view();
1744 std::string_view channel_type = channel->type()->string_view();
1745 const int channel_index =
1746 configuration::ChannelIndex(logged_configuration(), channel);
1747 // If the channel is remapped, find the correct channel name to use.
1748 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001749 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001750 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001751 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001752 }
1753
Austin Schuhee711052020-08-24 16:06:09 -07001754 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001755 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001756 configuration(), channel_name, channel_type,
1757 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001758
1759 CHECK(remapped_channel != nullptr)
1760 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1761 << channel_type << "\"} because it is not in the provided configuration.";
1762
1763 return remapped_channel;
1764}
1765
James Kuszmaul09632422022-05-25 15:56:19 -07001766LogReader::State::State(
1767 std::unique_ptr<TimestampMapper> timestamp_mapper,
1768 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaulb11a1502022-07-01 16:02:25 -07001769 std::function<void()> notice_realtime_end, const Node *node,
1770 LogReader::State::ThreadedBuffering threading,
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001771 std::unique_ptr<const ReplayChannelIndices> replay_channel_indices,
1772 const std::vector<std::function<void(void *message)>>
1773 &before_send_callbacks)
James Kuszmaul09632422022-05-25 15:56:19 -07001774 : timestamp_mapper_(std::move(timestamp_mapper)),
James Kuszmaulb11a1502022-07-01 16:02:25 -07001775 notice_realtime_end_(notice_realtime_end),
James Kuszmaul09632422022-05-25 15:56:19 -07001776 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001777 multinode_filters_(multinode_filters),
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001778 threading_(threading),
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001779 replay_channel_indices_(std::move(replay_channel_indices)),
1780 before_send_callbacks_(before_send_callbacks) {
Naman Guptaa68401c2022-12-08 14:34:06 -08001781 // If timestamp_mapper_ is nullptr, then there are no log parts associated
1782 // with this node. If there are no log parts for the node, there will be no
1783 // log data, and so we do not need to worry about the replay channel filters.
1784 if (replay_channel_indices_ != nullptr && timestamp_mapper_ != nullptr) {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001785 timestamp_mapper_->set_replay_channels_callback(
Naman Guptacf6d4422023-03-01 11:41:00 -08001786 [filter = replay_channel_indices_.get()](
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07001787 const TimestampedMessage &message) -> bool {
1788 auto const begin = filter->cbegin();
1789 auto const end = filter->cend();
1790 // TODO: benchmark strategies for channel_index matching
1791 return std::binary_search(begin, end, message.channel_index);
1792 });
1793 }
1794}
Austin Schuh287d43d2020-12-04 20:19:33 -08001795
1796void LogReader::State::AddPeer(State *peer) {
1797 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1798 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1799 }
1800}
Austin Schuh858c9f32020-08-31 16:56:12 -07001801
Austin Schuh58646e22021-08-23 23:51:46 -07001802void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001803 NodeEventLoopFactory *node_event_loop_factory,
1804 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001805 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001806 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001807}
1808
1809void LogReader::State::SetChannelCount(size_t count) {
1810 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001811 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001812 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001813 channel_source_state_.resize(count);
1814 factory_channel_index_.resize(count);
1815 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001816}
1817
Austin Schuh58646e22021-08-23 23:51:46 -07001818void LogReader::State::SetRemoteTimestampSender(
1819 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1820 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1821}
1822
Austin Schuh858c9f32020-08-31 16:56:12 -07001823void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001824 size_t logged_channel_index, size_t factory_channel_index,
1825 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001826 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1827 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001828 channels_[logged_channel_index] = std::move(sender);
1829 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001830 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001831
Austin Schuh58646e22021-08-23 23:51:46 -07001832 if (is_forwarded) {
1833 queue_index_map_[logged_channel_index] =
1834 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001835 }
1836
1837 factory_channel_index_[logged_channel_index] = factory_channel_index;
1838}
1839
James Kuszmaula16a7912022-06-17 10:58:12 -07001840void LogReader::State::TrackMessageSendTiming(
1841 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1842 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1843 return;
1844 }
1845
1846 timing::MessageTimingT sample;
1847 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1848 sender.channel());
1849 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1850 sample.actual_send_time =
1851 sender.monotonic_sent_time().time_since_epoch().count();
1852 sample.send_time_error = aos::time::DurationInSeconds(
1853 expected_send_time - sender.monotonic_sent_time());
1854 send_timings_.push_back(sample);
1855
1856 // Somewhat arbitrarily send out timing information in batches of 100. No need
1857 // to create excessive overhead in regenerated logfiles.
1858 // TODO(james): The overhead may be fine.
1859 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1860 CHECK(timing_statistics_sender_.valid());
1861 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1862 SendMessageTimings();
1863 }
1864}
1865
1866void LogReader::State::SendMessageTimings() {
1867 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1868 return;
1869 }
1870 auto builder = timing_statistics_sender_.MakeBuilder();
1871 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1872 for (const auto &timing : send_timings_) {
1873 timing_offsets.push_back(
1874 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1875 }
1876 send_timings_.clear();
1877 flatbuffers::Offset<
1878 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1879 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1880 timing::ReplayTiming::Builder timing_builder =
1881 builder.MakeBuilder<timing::ReplayTiming>();
1882 timing_builder.add_messages(timings_offset);
1883 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1884}
1885
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001886bool LogReader::State::Send(const TimestampedMessage &&timestamped_message) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001887 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001888 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001889 uint32_t remote_queue_index = 0xffffffff;
1890
Austin Schuh287d43d2020-12-04 20:19:33 -08001891 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001892 State *source_state =
1893 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001894 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001895 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001896 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001897
Austin Schuh9942bae2021-01-07 22:06:44 -08001898 struct SentTimestamp {
1899 monotonic_clock::time_point monotonic_event_time;
1900 uint32_t queue_index;
1901 } search;
1902
Austin Schuh58646e22021-08-23 23:51:46 -07001903 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1904 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001905 search.monotonic_event_time =
1906 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001907 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001908
1909 // Find the sent time if available.
1910 auto element = std::lower_bound(
1911 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001912 [](ContiguousSentTimestamp a, SentTimestamp b) {
1913 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001914 return true;
1915 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001916 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001917 return false;
1918 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001919
1920 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001921 return true;
1922 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001923 if (a.starting_queue_index >= b.queue_index) {
1924 return false;
1925 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001926
Austin Schuh9942bae2021-01-07 22:06:44 -08001927 // If it isn't clearly below or above, it is below. Since we return
1928 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 return false;
1930 });
1931
1932 // TODO(austin): Be a bit more principled here, but we will want to do that
1933 // after the logger rewrite. We hit this when one node finishes, but the
1934 // other node isn't done yet. So there is no send time, but there is a
1935 // receive time.
1936 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001937 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1938 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001939
1940 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001941 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001942 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001943 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001944 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001945 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001946 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001947 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001948
Austin Schuh58646e22021-08-23 23:51:46 -07001949 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001950 element->actual_queue_index -
1951 element->starting_queue_index;
1952 } else {
1953 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001954 }
Austin Schuh58646e22021-08-23 23:51:46 -07001955 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1956 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001957 }
1958
James Kuszmaul09632422022-05-25 15:56:19 -07001959 if (event_loop_factory_ != nullptr &&
1960 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1961 multinode_filters_ != nullptr) {
1962 // Sanity check that we are using consistent boot uuids.
1963 State *source_state =
1964 channel_source_state_[timestamped_message.channel_index];
1965 CHECK_EQ(multinode_filters_->boot_uuid(
1966 configuration::GetNodeIndex(event_loop_->configuration(),
1967 source_state->node()),
1968 timestamped_message.monotonic_remote_time.boot),
1969 CHECK_NOTNULL(
1970 CHECK_NOTNULL(
1971 channel_source_state_[timestamped_message.channel_index])
1972 ->event_loop_)
1973 ->boot_uuid());
1974 }
1975
Eric Schmiedebergae00e732023-04-12 15:53:17 -06001976 // Right before sending allow the user to process the message.
1977 if (before_send_callbacks_[timestamped_message.channel_index]) {
1978 // Only channels that are forwarded and sent from this State's node will be
1979 // in the queue_index_map_
1980 if (queue_index_map_[timestamped_message.channel_index]) {
1981 before_send_callbacks_[timestamped_message.channel_index](
1982 timestamped_message.data->mutable_data());
1983 }
1984 }
1985
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001986 // Send! Use the replayed queue index here instead of the logged queue index
1987 // for the remote queue index. This makes re-logging work.
Austin Schuhaf8a0d32023-05-03 09:53:06 -07001988 const RawSender::Error err = sender->Send(
Austin Schuhe0ab4de2023-05-03 08:05:08 -07001989 SharedSpan(timestamped_message.data, &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001990 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001991 timestamped_message.realtime_remote_time, remote_queue_index,
1992 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001993 ? CHECK_NOTNULL(multinode_filters_)
1994 ->boot_uuid(configuration::GetNodeIndex(
1995 event_loop_->configuration(),
1996 channel_source_state_[timestamped_message
1997 .channel_index]
1998 ->node()),
1999 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07002000 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07002001 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07002002 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
2003 timestamped_message.monotonic_event_time.time) {
2004 // Only track errors for non-fetched messages.
2005 TrackMessageSendTiming(
2006 *sender,
2007 timestamped_message.monotonic_event_time.time + clock_offset());
2008 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002009
Austin Schuh287d43d2020-12-04 20:19:33 -08002010 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07002011 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08002012 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
2013 // Nothing here, start a range with 0 length.
2014 ContiguousSentTimestamp timestamp;
2015 timestamp.starting_monotonic_event_time =
2016 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002017 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002018 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002019 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002020 timestamp.actual_queue_index = sender->sent_queue_index();
2021 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2022 timestamp);
2023 } else {
2024 // We've got something. See if the next timestamp is still contiguous. If
2025 // so, grow it.
2026 ContiguousSentTimestamp *back =
2027 &queue_index_map_[timestamped_message.channel_index]->back();
2028 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07002029 (timestamped_message.queue_index.index -
2030 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07002031 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002032 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002033 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002034 } else {
2035 // Otherwise, make a new one.
2036 ContiguousSentTimestamp timestamp;
2037 timestamp.starting_monotonic_event_time =
2038 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002039 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08002040 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07002041 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08002042 timestamp.actual_queue_index = sender->sent_queue_index();
2043 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2044 timestamp);
2045 }
2046 }
2047
2048 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2049 // queue index diverge a couple of elements, which would be a very small
2050 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002051 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2052 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07002053 // TODO(james): Currently, If running replay against a single event loop,
2054 // remote timestamps will not get replayed because this code-path only
2055 // gets triggered on the event loop that receives the forwarded message
2056 // that the timestamps correspond to. This code, as written, also doesn't
2057 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07002058 State *source_state =
2059 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
2060
Austin Schuh969cd602021-01-03 00:09:45 -08002061 flatbuffers::FlatBufferBuilder fbb;
2062 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07002063 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
2064 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08002065
Austin Schuh969cd602021-01-03 00:09:45 -08002066 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002067
2068 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002069 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002070
2071 // Swap the remote and sent metrics. They are from the sender's
2072 // perspective, not the receiver's perspective.
2073 message_header_builder.add_monotonic_sent_time(
2074 sender->monotonic_sent_time().time_since_epoch().count());
2075 message_header_builder.add_realtime_sent_time(
2076 sender->realtime_sent_time().time_since_epoch().count());
2077 message_header_builder.add_queue_index(sender->sent_queue_index());
2078
Austin Schuh58646e22021-08-23 23:51:46 -07002079 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
2080 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002081 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002082 timestamped_message.monotonic_remote_time.time.time_since_epoch()
2083 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002084 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002085 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002086
2087 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002088 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002089
Austin Schuh969cd602021-01-03 00:09:45 -08002090 fbb.Finish(message_header_builder.Finish());
2091
2092 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2093 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07002094 timestamped_message.monotonic_timestamp_time,
2095 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002096 }
2097
2098 return true;
2099}
2100
Austin Schuh969cd602021-01-03 00:09:45 -08002101LogReader::RemoteMessageSender::RemoteMessageSender(
2102 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2103 : event_loop_(event_loop),
2104 sender_(std::move(sender)),
2105 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2106
2107void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2108 if (remote_timestamps_.empty()) {
2109 CHECK_NOTNULL(timer_);
2110 timer_->Disable();
2111 scheduled_time_ = monotonic_clock::min_time;
2112 return;
2113 }
2114
2115 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2116 CHECK_NOTNULL(timer_);
Philipp Schradera6712522023-07-05 20:25:11 -07002117 timer_->Schedule(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002118 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002119 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2120 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002121 }
2122}
2123
2124void LogReader::RemoteMessageSender::Send(
2125 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002126 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002127 // There are 2 variants of logs.
2128 // 1) Logs without monotonic_timestamp_time
2129 // 2) Logs with monotonic_timestamp_time
2130 //
2131 // As of Jan 2021, we shouldn't have any more logs without
2132 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2133 // the effort of saving.
2134 //
2135 // This gives us 3 cases, 2 of which are undistinguishable.
2136 // 1) Old log without monotonic_timestamp_time.
2137 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2138 // remotely so we actually have monotonic_timestamp_time.
2139 // 3) New log, but the timestamp was logged on the node receiving the message
2140 // so there is no monotonic_timestamp_time.
2141 //
2142 // Our goal when replaying is to accurately reproduce the state of the world
2143 // present when logging. If a timestamp wasn't sent back across the network,
2144 // we shouldn't replay one back across the network.
2145 //
2146 // Given that we don't really care about 1, we can use the presence of the
2147 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2148 // monotonic_timestamp_time, this means the message was logged locally and
2149 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002150 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002151 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002152 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002153
Austin Schuh58646e22021-08-23 23:51:46 -07002154 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2155
Austin Schuhc41d6a82021-07-16 14:49:23 -07002156 remote_timestamps_.emplace(
2157 std::upper_bound(
2158 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002159 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002160 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2161 const Timestamp &timestamp) {
2162 return monotonic_timestamp_time <
2163 timestamp.monotonic_timestamp_time;
2164 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002165 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002166 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002167}
2168
2169void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002170 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2171 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002172 CHECK(!remote_timestamps_.empty());
2173
2174 // Send out all timestamps at the currently scheduled time.
2175 while (remote_timestamps_.front().monotonic_timestamp_time ==
2176 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002177 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2178 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002179 remote_timestamps_.pop_front();
2180 if (remote_timestamps_.empty()) {
2181 break;
2182 }
2183 }
2184 scheduled_time_ = monotonic_clock::min_time;
2185
2186 ScheduleTimestamp();
2187}
2188
2189LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002190 const Channel *channel, const Connection *connection) {
2191 message_bridge::ChannelTimestampFinder finder(event_loop_);
2192 // Look at any pre-created channel/connection pairs.
2193 {
2194 auto it =
2195 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2196 if (it != channel_timestamp_loggers_.end()) {
2197 return it->second.get();
2198 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002199 }
2200
Austin Schuh61e973f2021-02-21 21:43:56 -08002201 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2202 // to.
2203 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2204
2205 {
2206 // See if that has been created before. If so, cache it in
2207 // channel_timestamp_loggers_ and return.
2208 auto it = timestamp_loggers_.find(timestamp_channel);
2209 if (it != timestamp_loggers_.end()) {
2210 CHECK(channel_timestamp_loggers_
2211 .try_emplace(std::make_pair(channel, connection), it->second)
2212 .second);
2213 return it->second.get();
2214 }
2215 }
2216
2217 // Otherwise, make a sender, save it, and cache it.
2218 auto result = channel_timestamp_loggers_.try_emplace(
2219 std::make_pair(channel, connection),
2220 std::make_shared<RemoteMessageSender>(
2221 event_loop()->MakeSender<RemoteMessage>(
2222 timestamp_channel->name()->string_view()),
2223 event_loop()));
2224
2225 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2226 .second);
2227 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002228}
2229
Austin Schuhdda74ec2021-01-03 19:30:37 -08002230TimestampedMessage LogReader::State::PopOldest() {
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002231 // multithreaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002232 if (message_queuer_.has_value()) {
2233 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2234 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2235 message_queuer_->SetState(
2236 message.value().monotonic_event_time +
2237 std::chrono::duration_cast<std::chrono::nanoseconds>(
2238 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2239 return message.value();
Eric Schmiedebergb38477e2022-12-02 16:08:04 -07002240 } else { // single threaded
James Kuszmaula16a7912022-06-17 10:58:12 -07002241 CHECK(timestamp_mapper_ != nullptr);
2242 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2243 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002244
James Kuszmaula16a7912022-06-17 10:58:12 -07002245 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002246
Alexei Strots036d84e2023-05-03 16:05:12 -07002247 VLOG(2) << "Node '" << MaybeNodeName(event_loop_->node())
2248 << "': PopOldest Popping " << result.monotonic_event_time;
James Kuszmaula16a7912022-06-17 10:58:12 -07002249 timestamp_mapper_->PopFront();
2250 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002251
James Kuszmaula16a7912022-06-17 10:58:12 -07002252 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002253
James Kuszmaula16a7912022-06-17 10:58:12 -07002254 VLOG(1) << "Popped " << result
2255 << configuration::CleanedChannelToString(
2256 event_loop_->configuration()->channels()->Get(
2257 factory_channel_index_[result.channel_index]));
2258 return result;
2259 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002260}
2261
James Kuszmaula16a7912022-06-17 10:58:12 -07002262BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2263 if (!message_queuer_.has_value()) {
2264 return SingleThreadedOldestMessageTime();
2265 }
2266 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2267 if (!message.has_value()) {
2268 return BootTimestamp::max_time();
2269 }
2270 if (message.value().monotonic_event_time.boot == boot_count()) {
2271 ObserveNextMessage(message.value().monotonic_event_time.time,
2272 message.value().realtime_event_time);
2273 }
2274 return message.value().monotonic_event_time;
2275}
2276
2277BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2278 CHECK(!message_queuer_.has_value())
2279 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2280 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002281 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002282 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002283 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002284 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2285 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002286 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002287 }
Alexei Strots036d84e2023-05-03 16:05:12 -07002288 VLOG(2) << "Node '" << MaybeNodeName(node()) << "': oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002289 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002290 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2291 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2292 result_ptr->realtime_event_time);
2293 }
Austin Schuh58646e22021-08-23 23:51:46 -07002294 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002295}
2296
2297void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002298 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002299
Austin Schuhe639ea12021-01-25 13:00:22 -08002300 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2301 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002302}
2303
2304void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002305 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002306 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002307 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002308 for (size_t i = 0; i < channels_.size(); ++i) {
2309 channels_[i].reset();
2310 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002311 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002312 channel_timestamp_loggers_.clear();
2313 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002314 event_loop_unique_ptr_.reset();
2315 event_loop_ = nullptr;
2316 timer_handler_ = nullptr;
2317 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002318 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002319}
2320
Austin Schuhe33c08d2022-02-03 18:15:21 -08002321void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2322 if (start_time != realtime_clock::min_time) {
2323 start_event_notifier_ = std::make_unique<EventNotifier>(
2324 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2325 }
2326}
2327
2328void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2329 if (end_time != realtime_clock::max_time) {
2330 end_event_notifier_ = std::make_unique<EventNotifier>(
2331 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2332 }
2333}
2334
2335void LogReader::State::ObserveNextMessage(
2336 monotonic_clock::time_point monotonic_event,
2337 realtime_clock::time_point realtime_event) {
2338 if (start_event_notifier_) {
2339 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2340 }
2341 if (end_event_notifier_) {
2342 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2343 }
2344}
2345
2346void LogReader::State::ClearTimeFlags() {
2347 start_event_notifier_.reset();
2348 end_event_notifier_.reset();
2349}
2350
2351void LogReader::State::NotifyLogfileStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002352 // If the start_event_notifier_ is set, that means that a realtime start time
2353 // was set manually; when the override is set, we want to delay any startup
2354 // handlers that would've happened before requested start time until that
2355 // start time.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002356 if (start_event_notifier_) {
Philipp Schrader790cb542023-07-05 21:06:52 -07002357 // Only call OnStart() if the start time for this node
2358 // (realtime_start_time())
Austin Schuhe33c08d2022-02-03 18:15:21 -08002359 if (start_event_notifier_->realtime_event_time() >
2360 realtime_start_time(boot_count())) {
2361 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2362 << " > " << realtime_start_time(boot_count());
2363 return;
2364 }
2365 }
2366 if (found_last_message_) {
2367 VLOG(1) << "Last message already found, bailing";
2368 return;
2369 }
2370 RunOnStart();
2371}
2372
2373void LogReader::State::NotifyFlagStart() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002374 // Should only be called if start_event_notifier_ has been set (which happens
2375 // as part of setting an explicit start time); only call the startup functions
2376 // that occurred *before* the start flag value.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002377 if (start_event_notifier_->realtime_event_time() >=
2378 realtime_start_time(boot_count())) {
2379 RunOnStart();
2380 }
2381}
2382
2383void LogReader::State::NotifyLogfileEnd() {
James Kuszmaul82c3b512023-07-08 20:25:41 -07002384 // Don't execute the OnEnd handlers if the logfile was ended artifically
2385 // early.
Austin Schuhe33c08d2022-02-03 18:15:21 -08002386 if (found_last_message_) {
2387 return;
2388 }
2389
James Kuszmaul82c3b512023-07-08 20:25:41 -07002390 // Ensure that we only call OnEnd() if OnStart() was already called for this
2391 // boot (and don't call OnEnd() twice).
Austin Schuhe33c08d2022-02-03 18:15:21 -08002392 if (!stopped_ && started_) {
2393 RunOnEnd();
2394 }
2395}
2396
2397void LogReader::State::NotifyFlagEnd() {
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 SetFoundLastMessage(true);
James Kuszmaulb11a1502022-07-01 16:02:25 -07002403 CHECK(notice_realtime_end_);
2404 notice_realtime_end_();
Austin Schuhe33c08d2022-02-03 18:15:21 -08002405 }
2406}
2407
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002408void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002409 if (node_event_loop_factory_ == nullptr) {
2410 // If not running with simulated event loop, set the monotonic clock
2411 // offset.
2412 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2413
2414 if (start_event_notifier_) {
2415 start_event_notifier_->SetClockOffset(clock_offset_);
2416 }
2417 if (end_event_notifier_) {
2418 end_event_notifier_->SetClockOffset(clock_offset_);
2419 }
2420 }
2421}
2422
James Kuszmaulb67409b2022-06-20 16:25:03 -07002423void LogReader::SetRealtimeReplayRate(double replay_rate) {
2424 CHECK(event_loop_factory_ != nullptr)
2425 << ": Can't set replay rate without an event loop factory (have you "
2426 "called Register()?).";
2427 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2428}
2429
James Kuszmaulb11a1502022-07-01 16:02:25 -07002430void LogReader::NoticeRealtimeEnd() {
2431 CHECK_GE(live_nodes_with_realtime_time_end_, 1u);
2432 --live_nodes_with_realtime_time_end_;
2433 if (live_nodes_with_realtime_time_end_ == 0 && exit_on_finish() &&
2434 event_loop_factory_ != nullptr) {
2435 event_loop_factory_->Exit();
2436 }
2437}
2438
Eric Schmiedebergae00e732023-04-12 15:53:17 -06002439bool LogReader::AreStatesInitialized() const {
2440 for (const auto &state : states_) {
2441 if (state) {
2442 return true;
2443 }
2444 }
2445 return false;
2446}
2447
Austin Schuhe309d2a2019-11-29 13:25:21 -08002448} // namespace logger
2449} // namespace aos