blob: b2d0ed9db3f8afe0f4e22681126f7aae2f0c5323 [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08007
Tyler Chatowbf0609c2021-07-31 16:13:27 -07008#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -08009#include <vector>
10
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070014#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070015#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080016#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070018#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080019#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080020#include "aos/network/remote_message_generated.h"
21#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080022#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080023#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070025#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070026#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080028#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080029
Austin Schuh15649d62019-12-28 16:36:38 -080030DEFINE_bool(skip_missing_forwarding_entries, false,
31 "If true, drop any forwarding entries with missing data. If "
32 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080033
Austin Schuh0ca1fd32020-12-18 22:53:05 -080034DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080035
Austin Schuh2f8fd752020-09-01 22:38:28 -070036DEFINE_bool(skip_order_validation, false,
37 "If true, ignore any out of orderness in replay");
38
Austin Schuhf0688662020-12-19 15:37:45 -080039DEFINE_double(
40 time_estimation_buffer_seconds, 2.0,
41 "The time to buffer ahead in the log file to accurately reconstruct time.");
42
Austin Schuhe33c08d2022-02-03 18:15:21 -080043DEFINE_string(
44 start_time, "",
45 "If set, start at this point in time in the log on the realtime clock.");
46DEFINE_string(
47 end_time, "",
48 "If set, end at this point in time in the log on the realtime clock.");
49
James Kuszmaul09632422022-05-25 15:56:19 -070050DEFINE_bool(drop_realtime_messages_before_start, false,
51 "If set, will drop any messages sent before the start of the "
52 "logfile in realtime replay. Setting this guarantees consistency "
53 "in timing with the original logfile, but means that you lose "
54 "access to fetched low-frequency messages.");
55
James Kuszmaula16a7912022-06-17 10:58:12 -070056DEFINE_double(
57 threaded_look_ahead_seconds, 2.0,
58 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
59 "Can validly be zero, but higher values are encouraged for realtime replay "
60 "in order to prevent the replay from ever having to block on waiting for "
61 "the reader to find the next message.");
62
Austin Schuhe309d2a2019-11-29 13:25:21 -080063namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070064namespace configuration {
65// We don't really want to expose this publicly, but log reader doesn't really
66// want to re-implement it.
67void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
68 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070069} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080070namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070071namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080072
Austin Schuh1c227352021-09-17 12:53:54 -070073bool CompareChannels(const Channel *c,
74 ::std::pair<std::string_view, std::string_view> p) {
75 int name_compare = c->name()->string_view().compare(p.first);
76 if (name_compare == 0) {
77 return c->type()->string_view() < p.second;
78 } else if (name_compare < 0) {
79 return true;
80 } else {
81 return false;
82 }
83}
84
85bool EqualsChannels(const Channel *c,
86 ::std::pair<std::string_view, std::string_view> p) {
87 return c->name()->string_view() == p.first &&
88 c->type()->string_view() == p.second;
89}
90
Austin Schuh0de30f32020-12-06 12:44:28 -080091// Copies the channel, removing the schema as we go. If new_name is provided,
92// it is used instead of the name inside the channel. If new_type is provided,
93// it is used instead of the type in the channel.
94flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
95 std::string_view new_name,
96 std::string_view new_type,
97 flatbuffers::FlatBufferBuilder *fbb) {
98 flatbuffers::Offset<flatbuffers::String> name_offset =
99 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
100 : new_name);
101 flatbuffers::Offset<flatbuffers::String> type_offset =
102 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
103 flatbuffers::Offset<flatbuffers::String> source_node_offset =
104 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
105 : 0;
106
107 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
108 destination_nodes_offset =
109 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
110
111 flatbuffers::Offset<
112 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
113 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
114
115 Channel::Builder channel_builder(*fbb);
116 channel_builder.add_name(name_offset);
117 channel_builder.add_type(type_offset);
118 if (c->has_frequency()) {
119 channel_builder.add_frequency(c->frequency());
120 }
121 if (c->has_max_size()) {
122 channel_builder.add_max_size(c->max_size());
123 }
124 if (c->has_num_senders()) {
125 channel_builder.add_num_senders(c->num_senders());
126 }
127 if (c->has_num_watchers()) {
128 channel_builder.add_num_watchers(c->num_watchers());
129 }
130 if (!source_node_offset.IsNull()) {
131 channel_builder.add_source_node(source_node_offset);
132 }
133 if (!destination_nodes_offset.IsNull()) {
134 channel_builder.add_destination_nodes(destination_nodes_offset);
135 }
136 if (c->has_logger()) {
137 channel_builder.add_logger(c->logger());
138 }
139 if (!logger_nodes_offset.IsNull()) {
140 channel_builder.add_logger_nodes(logger_nodes_offset);
141 }
142 if (c->has_read_method()) {
143 channel_builder.add_read_method(c->read_method());
144 }
145 if (c->has_num_readers()) {
146 channel_builder.add_num_readers(c->num_readers());
147 }
148 return channel_builder.Finish();
149}
150
Austin Schuhe309d2a2019-11-29 13:25:21 -0800151namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800152using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700153} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800154
Austin Schuhe33c08d2022-02-03 18:15:21 -0800155// Class to manage triggering events on the RT clock while replaying logs. Since
156// the RT clock can only change when we get a message, we only need to update
157// our timers when new messages are read.
158class EventNotifier {
159 public:
160 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
161 std::string_view name,
162 realtime_clock::time_point realtime_event_time)
163 : event_loop_(event_loop),
164 fn_(std::move(fn)),
165 realtime_event_time_(realtime_event_time) {
166 CHECK(event_loop_);
167 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
168
169 if (event_loop_->node() != nullptr) {
170 event_timer_->set_name(
171 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
172 } else {
173 event_timer_->set_name(name);
174 }
175 }
176
177 ~EventNotifier() { event_timer_->Disable(); }
178
James Kuszmaul09632422022-05-25 15:56:19 -0700179 // Sets the clock offset for realtime playback.
180 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
181 clock_offset_ = clock_offset;
182 }
183
Austin Schuhe33c08d2022-02-03 18:15:21 -0800184 // Returns the event trigger time.
185 realtime_clock::time_point realtime_event_time() const {
186 return realtime_event_time_;
187 }
188
189 // Observes the next message and potentially calls the callback or updates the
190 // timer.
191 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
192 realtime_clock::time_point realtime_message_time) {
193 if (realtime_message_time < realtime_event_time_) {
194 return;
195 }
196 if (called_) {
197 return;
198 }
199
200 // Move the callback wakeup time to the correct time (or make it now if
201 // there's a gap in time) now that we know it is before the next
202 // message.
203 const monotonic_clock::time_point candidate_monotonic =
204 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
205 const monotonic_clock::time_point monotonic_now =
206 event_loop_->monotonic_now();
207 if (candidate_monotonic < monotonic_now) {
208 // Whops, time went backwards. Just do it now.
209 HandleTime();
210 } else {
James Kuszmaul09632422022-05-25 15:56:19 -0700211 event_timer_->Setup(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800212 }
213 }
214
215 private:
216 void HandleTime() {
217 if (!called_) {
218 called_ = true;
219 fn_();
220 }
221 }
222
223 EventLoop *event_loop_ = nullptr;
224 TimerHandler *event_timer_ = nullptr;
225 std::function<void()> fn_;
226
227 const realtime_clock::time_point realtime_event_time_ =
228 realtime_clock::min_time;
229
James Kuszmaul09632422022-05-25 15:56:19 -0700230 std::chrono::nanoseconds clock_offset_{0};
231
Austin Schuhe33c08d2022-02-03 18:15:21 -0800232 bool called_ = false;
233};
234
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800235LogReader::LogReader(std::string_view filename,
236 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800237 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800238
Austin Schuh287d43d2020-12-04 20:19:33 -0800239LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800240 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800241 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800242 replay_configuration_(replay_configuration) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800243 SetStartTime(FLAGS_start_time);
244 SetEndTime(FLAGS_end_time);
245
Austin Schuh0ca51f32020-12-25 21:51:45 -0800246 CHECK_GT(log_files_.size(), 0u);
247 {
248 // Validate that we have the same config everwhere. This will be true if
249 // all the parts were sorted together and the configs match.
250 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800251 for (const LogFile &log_file : log_files_) {
252 if (log_file.config.get() == nullptr) {
253 LOG(FATAL) << "Couldn't find a config in " << log_file;
254 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800255 if (config == nullptr) {
256 config = log_file.config.get();
257 } else {
258 CHECK_EQ(config, log_file.config.get());
259 }
260 }
261 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800262
Austin Schuh6331ef92020-01-07 18:28:09 -0800263 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800264
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700265 // Remap all existing remote timestamp channels. They will be recreated, and
266 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700267 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800268 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
269 "log_reader", node);
270
271 absl::btree_set<std::string_view> remote_nodes;
272
273 for (const Channel *channel : *logged_configuration()->channels()) {
274 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
275 continue;
276 }
277 if (!channel->has_destination_nodes()) {
278 continue;
279 }
280 for (const Connection *connection : *channel->destination_nodes()) {
281 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
282 node)) {
283 // Start by seeing if the split timestamp channels are being used for
284 // this message. If so, remap them.
285 const Channel *timestamp_channel = configuration::GetChannel(
286 logged_configuration(),
287 finder.SplitChannelName(channel, connection),
288 RemoteMessage::GetFullyQualifiedName(), "", node, true);
289
290 if (timestamp_channel != nullptr) {
291 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
292 RemapLoggedChannel<RemoteMessage>(
293 timestamp_channel->name()->string_view(), node);
294 }
295 continue;
296 }
297
298 // Otherwise collect this one up as a node to look for a combined
299 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700300 LOG(WARNING) << "Failed to find channel "
301 << finder.SplitChannelName(channel, connection)
302 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800303 remote_nodes.insert(connection->name()->string_view());
304 }
305 }
306 }
307
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700308 std::vector<const Node *> timestamp_logger_nodes =
309 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800310 for (const std::string_view remote_node : remote_nodes) {
311 const std::string channel = finder.CombinedChannelName(remote_node);
312
Austin Schuh0de30f32020-12-06 12:44:28 -0800313 // See if the log file is an old log with MessageHeader channels in it, or
314 // a newer log with RemoteMessage. If we find an older log, rename the
315 // type too along with the name.
316 if (HasChannel<MessageHeader>(channel, node)) {
317 CHECK(!HasChannel<RemoteMessage>(channel, node))
318 << ": Can't have both a MessageHeader and RemoteMessage remote "
319 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800320 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
321 // careful about updating the config, but there are fewer and fewer logs
322 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800323 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
324 "aos.message_bridge.RemoteMessage");
325 } else {
326 CHECK(HasChannel<RemoteMessage>(channel, node))
327 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
328 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
329 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800330 // Only bother to remap if there's something on the channel. We can
331 // tell if the channel was marked NOT_LOGGED or not. This makes the
332 // config not change un-necesarily when we replay a log with NOT_LOGGED
333 // messages.
334 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
335 RemapLoggedChannel<RemoteMessage>(channel, node);
336 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800337 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700338 }
339 }
340
Austin Schuh6aa77be2020-02-22 21:06:40 -0800341 if (replay_configuration) {
342 CHECK_EQ(configuration::MultiNode(configuration()),
343 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700344 << ": Log file and replay config need to both be multi or single "
345 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800346 }
347
Austin Schuh6f3babe2020-01-26 20:34:50 -0800348 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700349 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800350 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800351 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700352 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800353 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700354 << ": Log file and replay config need to have matching nodes "
355 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700356 for (const Node *node : *logged_configuration()->nodes()) {
357 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
359 << " in logged config that is not present in the replay "
360 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700361 }
362 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800363 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800364 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800365 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800366}
367
Austin Schuh6aa77be2020-02-22 21:06:40 -0800368LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700369 if (event_loop_factory_unique_ptr_) {
370 Deregister();
371 } else if (event_loop_factory_ != nullptr) {
372 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
373 "is destroyed";
374 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700375 // Zero out some buffers. It's easy to do use-after-frees on these, so make
376 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700377 if (remapped_configuration_buffer_) {
378 remapped_configuration_buffer_->Wipe();
379 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800380}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800381
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800382const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800383 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800384}
385
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800386const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800387 return remapped_configuration_;
388}
389
Austin Schuh07676622021-01-21 18:59:17 -0800390std::vector<const Node *> LogReader::LoggedNodes() const {
391 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800392}
Austin Schuh15649d62019-12-28 16:36:38 -0800393
Austin Schuh11d43732020-09-21 17:28:30 -0700394monotonic_clock::time_point LogReader::monotonic_start_time(
395 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800396 State *state =
397 states_[configuration::GetNodeIndex(configuration(), node)].get();
398 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
399
Austin Schuhf665eb42022-02-03 18:26:25 -0800400 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800401}
402
Austin Schuh11d43732020-09-21 17:28:30 -0700403realtime_clock::time_point LogReader::realtime_start_time(
404 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800405 State *state =
406 states_[configuration::GetNodeIndex(configuration(), node)].get();
407 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
408
Austin Schuhf665eb42022-02-03 18:26:25 -0800409 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800410}
411
Austin Schuh58646e22021-08-23 23:51:46 -0700412void LogReader::OnStart(std::function<void()> fn) {
413 CHECK(!configuration::MultiNode(configuration()));
414 OnStart(nullptr, std::move(fn));
415}
416
417void LogReader::OnStart(const Node *node, std::function<void()> fn) {
418 const int node_index = configuration::GetNodeIndex(configuration(), node);
419 CHECK_GE(node_index, 0);
420 CHECK_LT(node_index, static_cast<int>(states_.size()));
421 State *state = states_[node_index].get();
422 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
423
424 state->OnStart(std::move(fn));
425}
426
James Kuszmaula16a7912022-06-17 10:58:12 -0700427void LogReader::State::QueueThreadUntil(BootTimestamp time) {
428 if (threading_ == ThreadedBuffering::kYes) {
429 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
430 message_queuer_.emplace(
431 [this](const BootTimestamp queue_until) {
432 // This will be called whenever anything prompts us for any state
433 // change; there may be wakeups that result in us not having any new
434 // data to push (even if we aren't done), in which case we will return
435 // nullopt but not done().
436 if (last_queued_message_.has_value() &&
437 queue_until < last_queued_message_) {
438 return util::ThreadedQueue<TimestampedMessage,
439 BootTimestamp>::PushResult{
440 std::nullopt, false,
441 last_queued_message_ == BootTimestamp::max_time()};
442 }
443 TimestampedMessage *message = timestamp_mapper_->Front();
444 // Upon reaching the end of the log, exit.
445 if (message == nullptr) {
446 last_queued_message_ = BootTimestamp::max_time();
447 return util::ThreadedQueue<TimestampedMessage,
448 BootTimestamp>::PushResult{std::nullopt,
449 false, true};
450 }
451 last_queued_message_ = message->monotonic_event_time;
452 const util::ThreadedQueue<TimestampedMessage,
453 BootTimestamp>::PushResult result{
454 *message, queue_until >= last_queued_message_, false};
455 timestamp_mapper_->PopFront();
456 SeedSortedMessages();
457 return result;
458 },
459 time);
460 // Spin until the first few seconds of messages are queued up so that we
461 // don't end up with delays/inconsistent timing during the first few seconds
462 // of replay.
463 message_queuer_->WaitForNoMoreWork();
464 }
465}
466
Austin Schuh58646e22021-08-23 23:51:46 -0700467void LogReader::State::OnStart(std::function<void()> fn) {
468 on_starts_.emplace_back(std::move(fn));
469}
470
471void LogReader::State::RunOnStart() {
472 SetRealtimeOffset(monotonic_start_time(boot_count()),
473 realtime_start_time(boot_count()));
474
475 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
476 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800477 auto fn = [this]() {
478 for (size_t i = 0; i < on_starts_.size(); ++i) {
479 on_starts_[i]();
480 }
481 };
482 if (event_loop_factory_) {
483 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
484 } else {
485 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700486 }
487 stopped_ = false;
488 started_ = true;
489}
490
491void LogReader::OnEnd(std::function<void()> fn) {
492 CHECK(!configuration::MultiNode(configuration()));
493 OnEnd(nullptr, std::move(fn));
494}
495
496void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
497 const int node_index = configuration::GetNodeIndex(configuration(), node);
498 CHECK_GE(node_index, 0);
499 CHECK_LT(node_index, static_cast<int>(states_.size()));
500 State *state = states_[node_index].get();
501 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
502
503 state->OnEnd(std::move(fn));
504}
505
506void LogReader::State::OnEnd(std::function<void()> fn) {
507 on_ends_.emplace_back(std::move(fn));
508}
509
510void LogReader::State::RunOnEnd() {
511 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
512 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800513 auto fn = [this]() {
514 for (size_t i = 0; i < on_ends_.size(); ++i) {
515 on_ends_[i]();
516 }
517 };
518 if (event_loop_factory_) {
519 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
520 } else {
521 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700522 }
523
524 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800525 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700526 if (message_queuer_.has_value()) {
527 message_queuer_->StopPushing();
528 }
Austin Schuh58646e22021-08-23 23:51:46 -0700529}
530
James Kuszmaul94ca5132022-07-19 09:11:08 -0700531std::vector<
532 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
533LogReader::State::NonExclusiveChannels() {
534 CHECK_NOTNULL(node_event_loop_factory_);
535 const aos::Configuration *config = node_event_loop_factory_->configuration();
536 std::vector<
537 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
538 result{// Timing reports can be sent by logged and replayed applications.
539 {aos::configuration::GetChannel(config, "/aos",
540 "aos.timing.Report", "", node_),
541 NodeEventLoopFactory::ExclusiveSenders::kNo},
542 // AOS_LOG may be used in the log and in replay.
543 {aos::configuration::GetChannel(
544 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
545 NodeEventLoopFactory::ExclusiveSenders::kNo}};
546 for (const Node *const node : configuration::GetNodes(config)) {
547 if (node == nullptr) {
548 break;
549 }
550 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
551 config,
552 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700553 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700554 // The old-style remote timestamp channel can be populated from any
555 // channel, simulated or replayed.
556 if (old_timestamp_channel != nullptr) {
557 result.push_back(std::make_pair(
558 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
559 }
560 }
561 // Remove any channels that weren't found due to not existing in the
562 // config.
563 for (size_t ii = 0; ii < result.size();) {
564 if (result[ii].first == nullptr) {
565 result.erase(result.begin() + ii);
566 } else {
567 ++ii;
568 }
569 }
570 return result;
571}
572
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800573void LogReader::Register() {
574 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800575 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800576 Register(event_loop_factory_unique_ptr_.get());
577}
578
Austin Schuh58646e22021-08-23 23:51:46 -0700579void LogReader::RegisterWithoutStarting(
580 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800581 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700582 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800583 filters_ =
584 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800585 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700586 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800587 chrono::duration_cast<chrono::nanoseconds>(
588 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800589
Austin Schuhe639ea12021-01-25 13:00:22 -0800590 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700591 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800592 const size_t node_index =
593 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800594 std::vector<LogParts> filtered_parts = FilterPartsForNode(
595 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800596
James Kuszmaula16a7912022-06-17 10:58:12 -0700597 // We don't run with threading on the buffering for simulated event loops
598 // because we haven't attempted to validate how the interactions beteen the
599 // buffering and the timestamp mapper works when running multiple nodes
600 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800601 states_[node_index] = std::make_unique<State>(
602 filtered_parts.size() == 0u
603 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700604 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700605 filters_.get(), node, State::ThreadedBuffering::kNo);
Austin Schuh8bd96322020-02-13 21:18:22 -0800606 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700607 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800608 event_loop_factory_->GetNodeEventLoopFactory(node),
609 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700610
611 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800612 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800613 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800614 filters_->SetTimestampMappers(std::move(timestamp_mappers));
615
616 // Note: this needs to be set before any times are pulled, or we won't observe
617 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800618 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700619
Austin Schuh287d43d2020-12-04 20:19:33 -0800620 for (const Node *node : configuration::GetNodes(configuration())) {
621 const size_t node_index =
622 configuration::GetNodeIndex(configuration(), node);
623 State *state = states_[node_index].get();
624 for (const Node *other_node : configuration::GetNodes(configuration())) {
625 const size_t other_node_index =
626 configuration::GetNodeIndex(configuration(), other_node);
627 State *other_state = states_[other_node_index].get();
628 if (other_state != state) {
629 state->AddPeer(other_state);
630 }
631 }
632 }
633
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700634 // Register after making all the State objects so we can build references
635 // between them.
636 for (const Node *node : configuration::GetNodes(configuration())) {
637 const size_t node_index =
638 configuration::GetNodeIndex(configuration(), node);
639 State *state = states_[node_index].get();
640
Austin Schuh58646e22021-08-23 23:51:46 -0700641 // If we didn't find any log files with data in them, we won't ever get a
642 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700643 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700644 continue;
645 }
646 ++live_nodes_;
647
648 NodeEventLoopFactory *node_factory =
649 event_loop_factory_->GetNodeEventLoopFactory(node);
650 node_factory->OnStartup([this, state, node]() {
651 RegisterDuringStartup(state->MakeEventLoop(), node);
652 });
653 node_factory->OnShutdown([this, state, node]() {
654 RegisterDuringStartup(nullptr, node);
655 state->DestroyEventLoop();
656 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700657 }
658
James Kuszmaul46d82582020-05-09 19:50:09 -0700659 if (live_nodes_ == 0) {
660 LOG(FATAL)
661 << "Don't have logs from any of the nodes in the replay config--are "
662 "you sure that the replay config matches the original config?";
663 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800664
Austin Schuh87dd3832021-01-01 23:07:31 -0800665 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800666
Austin Schuh858c9f32020-08-31 16:56:12 -0700667 for (std::unique_ptr<State> &state : states_) {
668 state->SeedSortedMessages();
669 }
670
Austin Schuh6f3babe2020-01-26 20:34:50 -0800671 // Forwarding is tracked per channel. If it is enabled, we want to turn it
672 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700673 // nodes, and also replayed on the other nodes. This may not satisfy all
674 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800675 if (configuration::MultiNode(event_loop_factory_->configuration())) {
676 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
677 const Channel *channel = logged_configuration()->channels()->Get(i);
678 const Node *node = configuration::GetNode(
679 configuration(), channel->source_node()->string_view());
680
Austin Schuh8bd96322020-02-13 21:18:22 -0800681 State *state =
682 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800683
684 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700685 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800686
687 event_loop_factory_->DisableForwarding(remapped_channel);
688 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700689
690 // If we are replaying a log, we don't want a bunch of redundant messages
691 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700692 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800693 }
Austin Schuh891214d2021-11-11 20:35:02 -0800694
695 // Write pseudo start times out to file now that we are all setup.
696 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700697}
698
699void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
700 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800701 StartAfterRegister(event_loop_factory);
702}
703
704void LogReader::StartAfterRegister(
705 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700706 // We want to start the log file at the last start time of the log files
707 // from all the nodes. Compute how long each node's simulation needs to run
708 // to move time to this point.
709 distributed_clock::time_point start_time = distributed_clock::min_time;
710
711 // TODO(austin): We want an "OnStart" callback for each node rather than
712 // running until the last node.
713
714 for (std::unique_ptr<State> &state : states_) {
715 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
716 << " for node " << MaybeNodeName(state->node()) << "now "
717 << state->monotonic_now();
718 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
719 continue;
720 }
721 // And start computing the start time on the distributed clock now that
722 // that works.
723 start_time = std::max(
724 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
725 }
726
727 // TODO(austin): If a node doesn't have a start time, we might not queue
728 // enough. If this happens, we'll explode with a frozen error eventually.
729
730 CHECK_GE(start_time, distributed_clock::epoch())
731 << ": Hmm, we have a node starting before the start of time. Offset "
732 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800733
Austin Schuhcde938c2020-02-02 17:30:07 -0800734 // While we are starting the system up, we might be relying on matching data
735 // to timestamps on log files where the timestamp log file starts before the
736 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800737 {
738 const bool prior_ignore_missing_data = ignore_missing_data_;
739 ignore_missing_data_ = true;
740 VLOG(1) << "Running until " << start_time << " in Register";
741 event_loop_factory_->RunFor(start_time.time_since_epoch());
742 VLOG(1) << "At start time";
743 // Now that we are running for real, missing data means that the log file is
744 // corrupted or went wrong.
745 ignore_missing_data_ = prior_ignore_missing_data;
746 }
Austin Schuh92547522019-12-28 14:33:43 -0800747
Austin Schuh8bd96322020-02-13 21:18:22 -0800748 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700749 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700750 if (state->realtime_start_time(0) != realtime_clock::min_time) {
751 state->SetRealtimeOffset(state->monotonic_start_time(0),
752 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700753 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700754 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
755 << " for node " << MaybeNodeName(state->event_loop()->node())
756 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700757 }
758
759 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800760 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800761 }
762}
763
Austin Schuh2f8fd752020-09-01 22:38:28 -0700764message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800765 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800766 if (filters_) {
767 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800768 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800769 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800770}
771
James Kuszmaul09632422022-05-25 15:56:19 -0700772// TODO(jkuszmaul): Make in-line modifications to
773// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
774// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800775void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700776 filters_ =
777 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
778 event_loop->configuration(), logged_configuration(),
779 log_files_[0].boots, FLAGS_skip_order_validation,
780 chrono::duration_cast<chrono::nanoseconds>(
781 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
782
783 std::vector<TimestampMapper *> timestamp_mappers;
784 for (const Node *node : configuration::GetNodes(configuration())) {
785 const size_t node_index =
786 configuration::GetNodeIndex(configuration(), node);
787 std::vector<LogParts> filtered_parts = FilterPartsForNode(
788 log_files_, node != nullptr ? node->name()->string_view() : "");
789
790 states_[node_index] = std::make_unique<State>(
791 filtered_parts.size() == 0u
792 ? nullptr
793 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700794 filters_.get(), node, State::ThreadedBuffering::kYes);
James Kuszmaul09632422022-05-25 15:56:19 -0700795 State *state = states_[node_index].get();
796
797 state->SetChannelCount(logged_configuration()->channels()->size());
798 timestamp_mappers.emplace_back(state->timestamp_mapper());
799 }
800
801 filters_->SetTimestampMappers(std::move(timestamp_mappers));
802
803 for (const Node *node : configuration::GetNodes(configuration())) {
804 const size_t node_index =
805 configuration::GetNodeIndex(configuration(), node);
806 State *state = states_[node_index].get();
807 for (const Node *other_node : configuration::GetNodes(configuration())) {
808 const size_t other_node_index =
809 configuration::GetNodeIndex(configuration(), other_node);
810 State *other_state = states_[other_node_index].get();
811 if (other_state != state) {
812 state->AddPeer(other_state);
813 }
814 }
815 }
816 for (const Node *node : configuration::GetNodes(configuration())) {
817 if (node == nullptr || node->name()->string_view() ==
818 event_loop->node()->name()->string_view()) {
819 Register(event_loop, event_loop->node());
820 } else {
821 Register(nullptr, node);
822 }
823 }
Austin Schuh58646e22021-08-23 23:51:46 -0700824}
825
826void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800827 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700828 states_[configuration::GetNodeIndex(configuration(), node)].get();
829
830 // If we didn't find any log files with data in them, we won't ever get a
831 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700832 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700833 return;
834 }
James Kuszmaul09632422022-05-25 15:56:19 -0700835
836 if (event_loop != nullptr) {
837 ++live_nodes_;
838 }
Austin Schuh58646e22021-08-23 23:51:46 -0700839
840 if (event_loop_factory_ != nullptr) {
841 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
842 [this, event_loop, node]() {
843 RegisterDuringStartup(event_loop, node);
844 });
845 } else {
846 RegisterDuringStartup(event_loop, node);
847 }
848}
849
850void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700851 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700852 CHECK(event_loop->configuration() == configuration());
853 }
854
855 State *state =
856 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800857
James Kuszmaul09632422022-05-25 15:56:19 -0700858 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800859 state->ClearTimeFlags();
860 }
861
Austin Schuh858c9f32020-08-31 16:56:12 -0700862 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800863
Tyler Chatow67ddb032020-01-12 14:30:04 -0800864 // We don't run timing reports when trying to print out logged data, because
865 // otherwise we would end up printing out the timing reports themselves...
866 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700867 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700868 event_loop->SkipTimingReport();
869 event_loop->SkipAosLog();
870 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800871
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700872 for (size_t logged_channel_index = 0;
873 logged_channel_index < logged_configuration()->channels()->size();
874 ++logged_channel_index) {
875 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700876 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700877 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800878
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700879 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700880 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700881
882 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700883
Austin Schuh58646e22021-08-23 23:51:46 -0700884 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
885 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700886 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700887 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800888
Austin Schuh58646e22021-08-23 23:51:46 -0700889 // We've got a message which is being forwarded to this node.
890 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700891
892 source_state =
893 states_[configuration::GetNodeIndex(configuration(), source_node)]
894 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800895 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700896
Austin Schuh58646e22021-08-23 23:51:46 -0700897 // We are the source, and it is forwarded.
898 const bool is_forwarded =
899 configuration::ChannelIsSendableOnNode(channel, node) &&
900 configuration::ConnectionCount(channel);
901
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700902 state->SetChannel(
903 logged_channel_index,
904 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700905 event_loop && logged &&
906 configuration::ChannelIsReadableOnNode(channel, node)
907 ? event_loop->MakeRawSender(channel)
908 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700909 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700910
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700911 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700912 const Node *source_node = configuration::GetNode(
913 configuration(), channel->source_node()->string_view());
914
915 for (const Connection *connection : *channel->destination_nodes()) {
916 const bool delivery_time_is_logged =
917 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
918 source_node);
919
920 if (delivery_time_is_logged) {
921 State *destination_state =
922 states_[configuration::GetNodeIndex(
923 configuration(), connection->name()->string_view())]
924 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700925 if (destination_state) {
926 destination_state->SetRemoteTimestampSender(
927 logged_channel_index,
928 event_loop ? state->RemoteTimestampSender(channel, connection)
929 : nullptr);
930 }
Austin Schuh58646e22021-08-23 23:51:46 -0700931 }
932 }
933 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800934 }
935
Austin Schuh58646e22021-08-23 23:51:46 -0700936 if (!event_loop) {
937 state->ClearRemoteTimestampSenders();
938 state->set_timer_handler(nullptr);
939 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800940 return;
941 }
942
Austin Schuh858c9f32020-08-31 16:56:12 -0700943 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700944 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800945 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700946 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700947 if (exit_on_finish_ && live_nodes_ == 0 &&
948 event_loop_factory_ != nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -0700949 CHECK_NOTNULL(event_loop_factory_)->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800950 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800951 return;
952 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700953
Austin Schuhdda74ec2021-01-03 19:30:37 -0800954 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700955
956 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
957 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800958
Austin Schuhe309d2a2019-11-29 13:25:21 -0800959 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700960 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700961 if (event_loop_factory_ != nullptr) {
962 // Only enforce exact timing in simulation.
963 if (!FLAGS_skip_order_validation) {
964 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
965 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
966 << monotonic_now << " trying to send "
967 << timestamped_message.monotonic_event_time << " failure "
968 << state->DebugString();
969 } else if (BootTimestamp{.boot = state->boot_count(),
970 .time = monotonic_now} !=
971 timestamped_message.monotonic_event_time) {
972 LOG(WARNING) << "Check failed: monotonic_now == "
973 "timestamped_message.monotonic_event_time) ("
974 << monotonic_now << " vs. "
975 << timestamped_message.monotonic_event_time
976 << "): " << FlatbufferToJson(state->event_loop()->node())
977 << " Now " << monotonic_now << " trying to send "
978 << timestamped_message.monotonic_event_time << " failure "
979 << state->DebugString();
980 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700981 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800982
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700983 if (timestamped_message.monotonic_event_time.time >
984 state->monotonic_start_time(
985 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700986 event_loop_factory_ != nullptr ||
987 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800988 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800989 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -0700990 BootTimestamp::min_time() &&
991 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800992 // Confirm that the message was sent on the sending node before the
993 // destination node (this node). As a proxy, do this by making sure
994 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800995 //
996 // TODO(austin): <= means that the cause message (which we know) could
997 // happen after the effect even though we know they are at the same
998 // time. I doubt anyone will notice for a bit, but we should really
999 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001000 BootTimestamp monotonic_remote_now =
1001 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001002 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001003 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001004 monotonic_remote_now.boot)
1005 << state->event_loop()->node()->name()->string_view() << " to "
1006 << state->remote_node(timestamped_message.channel_index)
1007 ->name()
1008 ->string_view()
1009 << " while trying to send a message on "
1010 << configuration::CleanedChannelToString(
1011 logged_configuration()->channels()->Get(
1012 timestamped_message.channel_index))
1013 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001014 CHECK_LE(timestamped_message.monotonic_remote_time,
1015 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001017 << state->remote_node(timestamped_message.channel_index)
1018 ->name()
1019 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001020 << " while trying to send a message on "
1021 << configuration::CleanedChannelToString(
1022 logged_configuration()->channels()->Get(
1023 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001024 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001025 } else if (monotonic_remote_now.boot !=
1026 timestamped_message.monotonic_remote_time.boot) {
1027 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1028 << " vs "
1029 << timestamped_message.monotonic_remote_time.boot;
1030 } else if (timestamped_message.monotonic_remote_time >
1031 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001032 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001033 << "Check failed: timestamped_message.monotonic_remote_time < "
1034 "state->monotonic_remote_now(timestamped_message.channel_"
1035 "index) ("
1036 << timestamped_message.monotonic_remote_time << " vs. "
1037 << state->monotonic_remote_now(
1038 timestamped_message.channel_index)
1039 << ") " << state->event_loop()->node()->name()->string_view()
1040 << " to "
1041 << state->remote_node(timestamped_message.channel_index)
1042 ->name()
1043 ->string_view()
1044 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001045 << " ("
1046 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001047 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001048 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001049 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001050 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001051 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001052 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001053 << ") " << state->DebugString();
1054 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001055 }
1056
Austin Schuh15649d62019-12-28 16:36:38 -08001057 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001058 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001059 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001060
Austin Schuh2f8fd752020-09-01 22:38:28 -07001061 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001062 << timestamped_message.monotonic_event_time << " "
1063 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 // TODO(austin): std::move channel_data in and make that efficient in
1065 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001066 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001067 } else if (state->found_last_message() ||
1068 (!ignore_missing_data_ &&
1069 // When starting up, we can have data which was sent before
1070 // the log starts, but the timestamp was after the log
1071 // starts. This is unreasonable to avoid, so ignore the
1072 // missing data.
1073 timestamped_message.monotonic_remote_time.time >=
1074 state->monotonic_remote_start_time(
1075 timestamped_message.monotonic_remote_time.boot,
1076 timestamped_message.channel_index) &&
1077 !FLAGS_skip_missing_forwarding_entries)) {
1078 if (!state->found_last_message()) {
1079 // We've found a timestamp without data that we expect to have data
1080 // for. This likely means that we are at the end of the log file.
1081 // Record it and CHECK that in the rest of the log file, we don't find
1082 // any more data on that channel. Not all channels will end at the
1083 // same point in time since they can be in different files.
1084 VLOG(1) << "Found the last message on channel "
1085 << timestamped_message.channel_index << ", "
1086 << configuration::CleanedChannelToString(
1087 logged_configuration()->channels()->Get(
1088 timestamped_message.channel_index))
1089 << " on node " << MaybeNodeName(state->event_loop()->node())
1090 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001091
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001092 // The user might be working with log files from 1 node but forgot to
1093 // configure the infrastructure to log data for a remote channel on
1094 // that node. That can be very hard to debug, even though the log
1095 // reader is doing the right thing. At least log a warning in that
1096 // case and tell the user what is happening so they can either update
1097 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001098 const std::vector<std::string> logger_nodes =
1099 FindLoggerNodes(log_files_);
1100 if (logger_nodes.size()) {
1101 // We have old logs which don't have the logger nodes logged. In
1102 // that case, we can't be helpful :(
1103 bool data_logged = false;
1104 const Channel *channel = logged_configuration()->channels()->Get(
1105 timestamped_message.channel_index);
1106 for (const std::string &node : logger_nodes) {
1107 data_logged |=
1108 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1109 }
1110 if (!data_logged) {
1111 LOG(WARNING) << "Got a timestamp without any logfiles which "
1112 "could contain data for channel "
1113 << configuration::CleanedChannelToString(channel);
1114 LOG(WARNING) << "Only have logs logged on ["
1115 << absl::StrJoin(logger_nodes, ", ") << "]";
1116 LOG(WARNING)
1117 << "Dropping the rest of the data on "
1118 << state->event_loop()->node()->name()->string_view();
1119 LOG(WARNING)
1120 << "Consider using --skip_missing_forwarding_entries to "
1121 "bypass this, update your config to log it, or add data "
1122 "from one of the nodes it is logged on.";
1123 }
1124 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001125 // Now that we found the end of one channel, artificially stop the
1126 // rest by setting the found_last_message bit. It is confusing when
1127 // part of your data gets replayed but not all. The rest of them will
1128 // get dropped as they are replayed to keep memory usage down.
1129 state->SetFoundLastMessage(true);
1130
1131 // Vector storing if we've seen a nullptr message or not per channel.
1132 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001133 }
1134
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001135 // Make sure that once we have seen the last message on a channel,
1136 // data doesn't start back up again. If the user wants to play
1137 // through events like this, they can set
1138 // --skip_missing_forwarding_entries or ignore_missing_data_.
1139 if (timestamped_message.data == nullptr) {
1140 state->set_last_message(timestamped_message.channel_index);
1141 } else {
1142 if (state->last_message(timestamped_message.channel_index)) {
1143 LOG(FATAL) << "Found missing data in the middle of the log file on "
1144 "channel "
1145 << timestamped_message.channel_index << " "
1146 << configuration::StrippedChannelToString(
1147 logged_configuration()->channels()->Get(
1148 timestamped_message.channel_index))
1149 << " " << timestamped_message << " "
1150 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001151 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001152 }
Austin Schuh92547522019-12-28 14:33:43 -08001153 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001154 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001155 LOG(WARNING)
1156 << "Not sending data from before the start of the log file. "
1157 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1158 .count()
1159 << " start "
1160 << monotonic_start_time(state->node()).time_since_epoch().count()
1161 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001162 }
1163
James Kuszmaula16a7912022-06-17 10:58:12 -07001164 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001165 if (next_time != BootTimestamp::max_time()) {
1166 if (next_time.boot != state->boot_count()) {
1167 VLOG(1) << "Next message for "
1168 << MaybeNodeName(state->event_loop()->node())
1169 << "is on the next boot, " << next_time << " now is "
1170 << state->monotonic_now();
1171 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001172 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001173 return;
1174 }
James Kuszmaul09632422022-05-25 15:56:19 -07001175 if (event_loop_factory_ != nullptr) {
1176 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1177 << "wakeup for " << next_time.time << "("
1178 << state->ToDistributedClock(next_time.time)
1179 << " distributed), now is " << state->monotonic_now();
1180 } else {
1181 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1182 << "wakeup for " << next_time.time << ", now is "
1183 << state->monotonic_now();
1184 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001185 // TODO(james): This can result in negative times getting passed-through
1186 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001187 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001188 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001189 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1190 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001191 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001192 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001193 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001194 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001195 // Doesn't apply to single-EventLoop replay since the watchers in question
1196 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001197 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001198 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1199 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001200 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001201 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001202
Austin Schuh2f8fd752020-09-01 22:38:28 -07001203 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1204 << state->event_loop()->context().monotonic_event_time << " now "
1205 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001206 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001207
James Kuszmaula16a7912022-06-17 10:58:12 -07001208 state->SeedSortedMessages();
1209
1210 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001211 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001212 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1213 if (start_time_ != realtime_clock::min_time) {
1214 state->SetStartTimeFlag(start_time_);
1215 }
1216 if (end_time_ != realtime_clock::max_time) {
1217 state->SetEndTimeFlag(end_time_);
1218 }
Austin Schuh58646e22021-08-23 23:51:46 -07001219 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001220 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001221 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001222 // Queue up messages and then set clock offsets (we don't want to set
1223 // clock offsets before we've done the work of getting the first messages
1224 // primed).
1225 state->QueueThreadUntil(
1226 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1227 std::chrono::duration<double>(
1228 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaul09632422022-05-25 15:56:19 -07001229 state->SetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001230 state->Setup(next_time.time);
1231 state->SetupStartupTimer();
1232 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001233 }
1234}
1235
Austin Schuhe33c08d2022-02-03 18:15:21 -08001236void LogReader::SetEndTime(std::string end_time) {
1237 if (end_time.empty()) {
1238 SetEndTime(realtime_clock::max_time);
1239 } else {
1240 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1241 aos::realtime_clock::FromString(end_time);
1242 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1243 << "'. Expected a date in the format of "
1244 "2021-01-15_15-30-35.000000000.";
1245 SetEndTime(*parsed_end_time);
1246 }
1247}
1248
1249void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1250 end_time_ = end_time;
1251}
1252
1253void LogReader::SetStartTime(std::string start_time) {
1254 if (start_time.empty()) {
1255 SetStartTime(realtime_clock::min_time);
1256 } else {
1257 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1258 aos::realtime_clock::FromString(start_time);
1259 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1260 << "'. Expected a date in the format of "
1261 "2021-01-15_15-30-35.000000000.";
1262 SetStartTime(*parsed_start_time);
1263 }
1264}
1265
1266void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1267 start_time_ = start_time;
1268}
1269
Austin Schuhe309d2a2019-11-29 13:25:21 -08001270void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001271 // Make sure that things get destroyed in the correct order, rather than
1272 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001273 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001274 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001275 }
Austin Schuh92547522019-12-28 14:33:43 -08001276
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001277 event_loop_factory_unique_ptr_.reset();
1278 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001279}
1280
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001281void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001282 std::string_view add_prefix,
1283 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001284 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1285 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1286 if (channel->name()->str() == name &&
1287 channel->type()->string_view() == type) {
1288 CHECK_EQ(0u, remapped_channels_.count(ii))
1289 << "Already remapped channel "
1290 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001291 RemappedChannel remapped_channel;
1292 remapped_channel.remapped_name =
1293 std::string(add_prefix) + std::string(name);
1294 remapped_channel.new_type = new_type;
1295 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001296 VLOG(1) << "Remapping channel "
1297 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001298 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001299 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001300 return;
1301 }
1302 }
1303 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1304 << type;
1305}
1306
Austin Schuh01b4c352020-09-21 23:09:39 -07001307void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1308 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001309 std::string_view add_prefix,
1310 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001311 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1312 const Channel *remapped_channel =
1313 configuration::GetChannel(logged_configuration(), name, type, "", node);
1314 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1315 << "\", \"type\": \"" << type << "\"}";
1316 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1317 << "\"}";
1318 VLOG(1) << "Remapped "
1319 << aos::configuration::StrippedChannelToString(remapped_channel);
1320
1321 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1322 // we want it to degrade if the heuristics fail to just work.
1323 //
1324 // The easiest way to do this is going to be incredibly specific and verbose.
1325 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1326 // /original/0/spray. Then, create a map from /original/spray to
1327 // /original/0/spray for just the type we were asked for.
1328 if (name != remapped_channel->name()->string_view()) {
1329 MapT new_map;
1330 new_map.match = std::make_unique<ChannelT>();
1331 new_map.match->name = absl::StrCat(add_prefix, name);
1332 new_map.match->type = type;
1333 if (node != nullptr) {
1334 new_map.match->source_node = node->name()->str();
1335 }
1336 new_map.rename = std::make_unique<ChannelT>();
1337 new_map.rename->name =
1338 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1339 maps_.emplace_back(std::move(new_map));
1340 }
1341
1342 const size_t channel_index =
1343 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1344 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1345 << "Already remapped channel "
1346 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001347
1348 RemappedChannel remapped_channel_struct;
1349 remapped_channel_struct.remapped_name =
1350 std::string(add_prefix) +
1351 std::string(remapped_channel->name()->string_view());
1352 remapped_channel_struct.new_type = new_type;
1353 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001354 MakeRemappedConfig();
1355}
1356
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001357void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001358 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001359 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001360 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001361 << ": Can't change the mapping after the events are scheduled.";
1362 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001363 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001364
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001365 // If no remapping occurred and we are using the original config, then there
1366 // is nothing interesting to do here.
1367 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001368 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001369 return;
1370 }
1371 // Config to copy Channel definitions from. Use the specified
1372 // replay_configuration_ if it has been provided.
1373 const Configuration *const base_config = replay_configuration_ == nullptr
1374 ? logged_configuration()
1375 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001376
1377 // Create a config with all the channels, but un-sorted/merged. Collect up
1378 // the schemas while we do this. Call MergeConfiguration to sort everything,
1379 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001380
1381 // This is the builder that we use for the config containing all the new
1382 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001383 flatbuffers::FlatBufferBuilder fbb;
1384 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001385 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001386
1387 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1388 << ": Merging logic needs to be updated when the number of channel "
1389 "fields changes.";
1390
1391 // List of schemas.
1392 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1393 // Make sure our new RemoteMessage schema is in there for old logs without it.
1394 schema_map.insert(std::make_pair(
1395 RemoteMessage::GetFullyQualifiedName(),
1396 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1397 message_bridge::RemoteMessageSchema()))));
1398
1399 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001400 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001401 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001402 base_config, logged_configuration()->channels()->Get(pair.first), "",
1403 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001404 channel_offsets.emplace_back(
1405 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001406
1407 if (c->has_destination_nodes()) {
1408 for (const Connection *connection : *c->destination_nodes()) {
1409 switch (connection->timestamp_logger()) {
1410 case LoggerConfig::LOCAL_LOGGER:
1411 case LoggerConfig::NOT_LOGGED:
1412 // There is no timestamp channel associated with this, so ignore it.
1413 break;
1414
1415 case LoggerConfig::REMOTE_LOGGER:
1416 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1417 // We want to make a split timestamp channel regardless of what type
1418 // of log this used to be. No sense propagating the single
1419 // timestamp channel.
1420
1421 CHECK(connection->has_timestamp_logger_nodes());
1422 for (const flatbuffers::String *timestamp_logger_node :
1423 *connection->timestamp_logger_nodes()) {
1424 const Node *node = configuration::GetNode(
1425 logged_configuration(), timestamp_logger_node->string_view());
1426 message_bridge::ChannelTimestampFinder finder(
1427 logged_configuration(), "log_reader", node);
1428
1429 // We are assuming here that all the maps are setup correctly to
1430 // handle arbitrary timestamps. Apply the maps for this node to
1431 // see what name this ends up with.
1432 std::string name = finder.SplitChannelName(
1433 pair.second.remapped_name, c->type()->str(), connection);
1434 std::string unmapped_name = name;
1435 configuration::HandleMaps(logged_configuration()->maps(), &name,
1436 "aos.message_bridge.RemoteMessage",
1437 node);
1438 CHECK_NE(name, unmapped_name)
1439 << ": Remote timestamp channel was not remapped, this is "
1440 "very fishy";
1441 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1442 fbb.CreateString(name);
1443 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1444 fbb.CreateString("aos.message_bridge.RemoteMessage");
1445 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1446 fbb.CreateString(timestamp_logger_node->string_view());
1447
1448 // Now, build a channel. Don't log it, 2 senders, and match the
1449 // source frequency.
1450 Channel::Builder channel_builder(fbb);
1451 channel_builder.add_name(channel_name_offset);
1452 channel_builder.add_type(channel_type_offset);
1453 channel_builder.add_source_node(source_node_offset);
1454 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1455 channel_builder.add_num_senders(2);
1456 if (c->has_frequency()) {
1457 channel_builder.add_frequency(c->frequency());
1458 }
1459 channel_offsets.emplace_back(channel_builder.Finish());
1460 }
1461 break;
1462 }
1463 }
1464 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001465 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001466
Austin Schuh0de30f32020-12-06 12:44:28 -08001467 // Now reconstruct the original channels, translating types as needed
1468 for (const Channel *c : *base_config->channels()) {
1469 // Search for a mapping channel.
1470 std::string_view new_type = "";
1471 for (auto &pair : remapped_channels_) {
1472 const Channel *const remapped_channel =
1473 logged_configuration()->channels()->Get(pair.first);
1474 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1475 remapped_channel->type()->string_view() == c->type()->string_view()) {
1476 new_type = pair.second.new_type;
1477 break;
1478 }
1479 }
1480
1481 // Copy everything over.
1482 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1483
1484 // Add the schema if it doesn't exist.
1485 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1486 CHECK(c->has_schema());
1487 schema_map.insert(std::make_pair(c->type()->string_view(),
1488 RecursiveCopyFlatBuffer(c->schema())));
1489 }
1490 }
1491
1492 // The MergeConfiguration API takes a vector, not a map. Convert.
1493 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1494 while (!schema_map.empty()) {
1495 schemas.emplace_back(std::move(schema_map.begin()->second));
1496 schema_map.erase(schema_map.begin());
1497 }
1498
1499 // Create the Configuration containing the new channels that we want to add.
1500 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1501 channels_offset =
1502 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1503
1504 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001505 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001506 if (base_config->maps()) {
1507 for (const Map *map : *base_config->maps()) {
1508 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1509 }
1510 }
1511
1512 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001513 for (const MapT &map : maps_) {
1514 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001515 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001516 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001517 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001518 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001519 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001520 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1521 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001522 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001523 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001524 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001525 match_builder.add_name(match_name_offset);
1526 match_builder.add_type(match_type_offset);
1527 if (!map.match->source_node.empty()) {
1528 match_builder.add_source_node(match_source_node_offset);
1529 }
1530 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1531
Austin Schuh0de30f32020-12-06 12:44:28 -08001532 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001533 rename_builder.add_name(rename_name_offset);
1534 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1535
Austin Schuh0de30f32020-12-06 12:44:28 -08001536 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001537 map_builder.add_match(match_offset);
1538 map_builder.add_rename(rename_offset);
1539 map_offsets.emplace_back(map_builder.Finish());
1540 }
1541
Austin Schuh0de30f32020-12-06 12:44:28 -08001542 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1543 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001544
Austin Schuh0de30f32020-12-06 12:44:28 -08001545 // And copy everything else over.
1546 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1547 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1548
1549 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1550 applications_offset =
1551 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1552
1553 // Now insert everything else in unmodified.
1554 ConfigurationBuilder configuration_builder(fbb);
1555 if (!channels_offset.IsNull()) {
1556 configuration_builder.add_channels(channels_offset);
1557 }
1558 if (!maps_offsets.IsNull()) {
1559 configuration_builder.add_maps(maps_offsets);
1560 }
1561 if (!nodes_offset.IsNull()) {
1562 configuration_builder.add_nodes(nodes_offset);
1563 }
1564 if (!applications_offset.IsNull()) {
1565 configuration_builder.add_applications(applications_offset);
1566 }
1567
1568 if (base_config->has_channel_storage_duration()) {
1569 configuration_builder.add_channel_storage_duration(
1570 base_config->channel_storage_duration());
1571 }
1572
1573 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1574 << ": Merging logic needs to be updated when the number of configuration "
1575 "fields changes.";
1576
1577 fbb.Finish(configuration_builder.Finish());
1578
1579 // Clean it up and return it! By using MergeConfiguration here, we'll
1580 // actually get a deduplicated config for free too.
1581 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1582 configuration::MergeConfiguration(
1583 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1584
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001585 remapped_configuration_buffer_ =
1586 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001587 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001588
1589 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001590
1591 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001592}
1593
Austin Schuh1c227352021-09-17 12:53:54 -07001594std::vector<const Channel *> LogReader::RemappedChannels() const {
1595 std::vector<const Channel *> result;
1596 result.reserve(remapped_channels_.size());
1597 for (auto &pair : remapped_channels_) {
1598 const Channel *const logged_channel =
1599 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1600
1601 auto channel_iterator = std::lower_bound(
1602 remapped_configuration_->channels()->cbegin(),
1603 remapped_configuration_->channels()->cend(),
1604 std::make_pair(std::string_view(pair.second.remapped_name),
1605 logged_channel->type()->string_view()),
1606 CompareChannels);
1607
1608 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1609 CHECK(EqualsChannels(
1610 *channel_iterator,
1611 std::make_pair(std::string_view(pair.second.remapped_name),
1612 logged_channel->type()->string_view())));
1613 result.push_back(*channel_iterator);
1614 }
1615 return result;
1616}
1617
Austin Schuh6f3babe2020-01-26 20:34:50 -08001618const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001619 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001620 const Channel *channel) {
1621 std::string_view channel_name = channel->name()->string_view();
1622 std::string_view channel_type = channel->type()->string_view();
1623 const int channel_index =
1624 configuration::ChannelIndex(logged_configuration(), channel);
1625 // If the channel is remapped, find the correct channel name to use.
1626 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001627 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001628 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001629 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001630 }
1631
Austin Schuhee711052020-08-24 16:06:09 -07001632 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001633 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001634 configuration(), channel_name, channel_type,
1635 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001636
1637 CHECK(remapped_channel != nullptr)
1638 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1639 << channel_type << "\"} because it is not in the provided configuration.";
1640
1641 return remapped_channel;
1642}
1643
James Kuszmaul09632422022-05-25 15:56:19 -07001644LogReader::State::State(
1645 std::unique_ptr<TimestampMapper> timestamp_mapper,
1646 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaula16a7912022-06-17 10:58:12 -07001647 const Node *node, LogReader::State::ThreadedBuffering threading)
James Kuszmaul09632422022-05-25 15:56:19 -07001648 : timestamp_mapper_(std::move(timestamp_mapper)),
1649 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001650 multinode_filters_(multinode_filters),
1651 threading_(threading) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001652
1653void LogReader::State::AddPeer(State *peer) {
1654 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1655 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1656 }
1657}
Austin Schuh858c9f32020-08-31 16:56:12 -07001658
Austin Schuh58646e22021-08-23 23:51:46 -07001659void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001660 NodeEventLoopFactory *node_event_loop_factory,
1661 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001662 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001663 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001664}
1665
1666void LogReader::State::SetChannelCount(size_t count) {
1667 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001668 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001669 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001670 channel_source_state_.resize(count);
1671 factory_channel_index_.resize(count);
1672 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001673}
1674
Austin Schuh58646e22021-08-23 23:51:46 -07001675void LogReader::State::SetRemoteTimestampSender(
1676 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1677 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1678}
1679
Austin Schuh858c9f32020-08-31 16:56:12 -07001680void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001681 size_t logged_channel_index, size_t factory_channel_index,
1682 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001683 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1684 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001685 channels_[logged_channel_index] = std::move(sender);
1686 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001687 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001688
Austin Schuh58646e22021-08-23 23:51:46 -07001689 if (is_forwarded) {
1690 queue_index_map_[logged_channel_index] =
1691 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001692 }
1693
1694 factory_channel_index_[logged_channel_index] = factory_channel_index;
1695}
1696
James Kuszmaula16a7912022-06-17 10:58:12 -07001697void LogReader::State::TrackMessageSendTiming(
1698 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1699 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1700 return;
1701 }
1702
1703 timing::MessageTimingT sample;
1704 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1705 sender.channel());
1706 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1707 sample.actual_send_time =
1708 sender.monotonic_sent_time().time_since_epoch().count();
1709 sample.send_time_error = aos::time::DurationInSeconds(
1710 expected_send_time - sender.monotonic_sent_time());
1711 send_timings_.push_back(sample);
1712
1713 // Somewhat arbitrarily send out timing information in batches of 100. No need
1714 // to create excessive overhead in regenerated logfiles.
1715 // TODO(james): The overhead may be fine.
1716 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1717 CHECK(timing_statistics_sender_.valid());
1718 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1719 SendMessageTimings();
1720 }
1721}
1722
1723void LogReader::State::SendMessageTimings() {
1724 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1725 return;
1726 }
1727 auto builder = timing_statistics_sender_.MakeBuilder();
1728 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1729 for (const auto &timing : send_timings_) {
1730 timing_offsets.push_back(
1731 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1732 }
1733 send_timings_.clear();
1734 flatbuffers::Offset<
1735 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1736 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1737 timing::ReplayTiming::Builder timing_builder =
1738 builder.MakeBuilder<timing::ReplayTiming>();
1739 timing_builder.add_messages(timings_offset);
1740 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1741}
1742
Austin Schuh287d43d2020-12-04 20:19:33 -08001743bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1744 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001745 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001746 uint32_t remote_queue_index = 0xffffffff;
1747
Austin Schuh287d43d2020-12-04 20:19:33 -08001748 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001749 State *source_state =
1750 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001751 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001752 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001753 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001754
Austin Schuh9942bae2021-01-07 22:06:44 -08001755 struct SentTimestamp {
1756 monotonic_clock::time_point monotonic_event_time;
1757 uint32_t queue_index;
1758 } search;
1759
Austin Schuh58646e22021-08-23 23:51:46 -07001760 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1761 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001762 search.monotonic_event_time =
1763 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001764 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001765
1766 // Find the sent time if available.
1767 auto element = std::lower_bound(
1768 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001769 [](ContiguousSentTimestamp a, SentTimestamp b) {
1770 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001771 return true;
1772 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001773 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001774 return false;
1775 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001776
1777 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001778 return true;
1779 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001780 if (a.starting_queue_index >= b.queue_index) {
1781 return false;
1782 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001783
Austin Schuh9942bae2021-01-07 22:06:44 -08001784 // If it isn't clearly below or above, it is below. Since we return
1785 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001786 return false;
1787 });
1788
1789 // TODO(austin): Be a bit more principled here, but we will want to do that
1790 // after the logger rewrite. We hit this when one node finishes, but the
1791 // other node isn't done yet. So there is no send time, but there is a
1792 // receive time.
1793 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001794 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1795 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001796
1797 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001798 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001799 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001800 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001801 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001802 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001803 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001804 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001805
Austin Schuh58646e22021-08-23 23:51:46 -07001806 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001807 element->actual_queue_index -
1808 element->starting_queue_index;
1809 } else {
1810 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001811 }
Austin Schuh58646e22021-08-23 23:51:46 -07001812 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1813 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001814 }
1815
James Kuszmaul09632422022-05-25 15:56:19 -07001816 if (event_loop_factory_ != nullptr &&
1817 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1818 multinode_filters_ != nullptr) {
1819 // Sanity check that we are using consistent boot uuids.
1820 State *source_state =
1821 channel_source_state_[timestamped_message.channel_index];
1822 CHECK_EQ(multinode_filters_->boot_uuid(
1823 configuration::GetNodeIndex(event_loop_->configuration(),
1824 source_state->node()),
1825 timestamped_message.monotonic_remote_time.boot),
1826 CHECK_NOTNULL(
1827 CHECK_NOTNULL(
1828 channel_source_state_[timestamped_message.channel_index])
1829 ->event_loop_)
1830 ->boot_uuid());
1831 }
1832
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001833 // Send! Use the replayed queue index here instead of the logged queue index
1834 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001835 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001836 RawSender::SharedSpan(timestamped_message.data,
1837 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001838 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001839 timestamped_message.realtime_remote_time, remote_queue_index,
1840 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001841 ? CHECK_NOTNULL(multinode_filters_)
1842 ->boot_uuid(configuration::GetNodeIndex(
1843 event_loop_->configuration(),
1844 channel_source_state_[timestamped_message
1845 .channel_index]
1846 ->node()),
1847 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001848 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001849 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001850 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1851 timestamped_message.monotonic_event_time.time) {
1852 // Only track errors for non-fetched messages.
1853 TrackMessageSendTiming(
1854 *sender,
1855 timestamped_message.monotonic_event_time.time + clock_offset());
1856 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001857
Austin Schuh287d43d2020-12-04 20:19:33 -08001858 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001859 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001860 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1861 // Nothing here, start a range with 0 length.
1862 ContiguousSentTimestamp timestamp;
1863 timestamp.starting_monotonic_event_time =
1864 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001865 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001866 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001867 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001868 timestamp.actual_queue_index = sender->sent_queue_index();
1869 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1870 timestamp);
1871 } else {
1872 // We've got something. See if the next timestamp is still contiguous. If
1873 // so, grow it.
1874 ContiguousSentTimestamp *back =
1875 &queue_index_map_[timestamped_message.channel_index]->back();
1876 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001877 (timestamped_message.queue_index.index -
1878 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001879 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001880 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001881 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001882 } else {
1883 // Otherwise, make a new one.
1884 ContiguousSentTimestamp timestamp;
1885 timestamp.starting_monotonic_event_time =
1886 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001887 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001888 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001889 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001890 timestamp.actual_queue_index = sender->sent_queue_index();
1891 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1892 timestamp);
1893 }
1894 }
1895
1896 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1897 // queue index diverge a couple of elements, which would be a very small
1898 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001899 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1900 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07001901 // TODO(james): Currently, If running replay against a single event loop,
1902 // remote timestamps will not get replayed because this code-path only
1903 // gets triggered on the event loop that receives the forwarded message
1904 // that the timestamps correspond to. This code, as written, also doesn't
1905 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07001906 State *source_state =
1907 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1908
Austin Schuh969cd602021-01-03 00:09:45 -08001909 flatbuffers::FlatBufferBuilder fbb;
1910 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001911 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1912 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001913
Austin Schuh969cd602021-01-03 00:09:45 -08001914 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001915
1916 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001917 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001918
1919 // Swap the remote and sent metrics. They are from the sender's
1920 // perspective, not the receiver's perspective.
1921 message_header_builder.add_monotonic_sent_time(
1922 sender->monotonic_sent_time().time_since_epoch().count());
1923 message_header_builder.add_realtime_sent_time(
1924 sender->realtime_sent_time().time_since_epoch().count());
1925 message_header_builder.add_queue_index(sender->sent_queue_index());
1926
Austin Schuh58646e22021-08-23 23:51:46 -07001927 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1928 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001930 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1931 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001932 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001933 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001934
1935 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001936 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001937
Austin Schuh969cd602021-01-03 00:09:45 -08001938 fbb.Finish(message_header_builder.Finish());
1939
1940 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1941 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001942 timestamped_message.monotonic_timestamp_time,
1943 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001944 }
1945
1946 return true;
1947}
1948
Austin Schuh969cd602021-01-03 00:09:45 -08001949LogReader::RemoteMessageSender::RemoteMessageSender(
1950 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1951 : event_loop_(event_loop),
1952 sender_(std::move(sender)),
1953 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1954
1955void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1956 if (remote_timestamps_.empty()) {
1957 CHECK_NOTNULL(timer_);
1958 timer_->Disable();
1959 scheduled_time_ = monotonic_clock::min_time;
1960 return;
1961 }
1962
1963 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1964 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001965 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001966 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001967 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1968 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001969 }
1970}
1971
1972void LogReader::RemoteMessageSender::Send(
1973 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001974 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001975 // There are 2 variants of logs.
1976 // 1) Logs without monotonic_timestamp_time
1977 // 2) Logs with monotonic_timestamp_time
1978 //
1979 // As of Jan 2021, we shouldn't have any more logs without
1980 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1981 // the effort of saving.
1982 //
1983 // This gives us 3 cases, 2 of which are undistinguishable.
1984 // 1) Old log without monotonic_timestamp_time.
1985 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1986 // remotely so we actually have monotonic_timestamp_time.
1987 // 3) New log, but the timestamp was logged on the node receiving the message
1988 // so there is no monotonic_timestamp_time.
1989 //
1990 // Our goal when replaying is to accurately reproduce the state of the world
1991 // present when logging. If a timestamp wasn't sent back across the network,
1992 // we shouldn't replay one back across the network.
1993 //
1994 // Given that we don't really care about 1, we can use the presence of the
1995 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1996 // monotonic_timestamp_time, this means the message was logged locally and
1997 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001998 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001999 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002000 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002001
Austin Schuh58646e22021-08-23 23:51:46 -07002002 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2003
Austin Schuhc41d6a82021-07-16 14:49:23 -07002004 remote_timestamps_.emplace(
2005 std::upper_bound(
2006 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002007 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002008 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2009 const Timestamp &timestamp) {
2010 return monotonic_timestamp_time <
2011 timestamp.monotonic_timestamp_time;
2012 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002013 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002014 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002015}
2016
2017void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002018 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2019 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002020 CHECK(!remote_timestamps_.empty());
2021
2022 // Send out all timestamps at the currently scheduled time.
2023 while (remote_timestamps_.front().monotonic_timestamp_time ==
2024 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002025 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2026 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002027 remote_timestamps_.pop_front();
2028 if (remote_timestamps_.empty()) {
2029 break;
2030 }
2031 }
2032 scheduled_time_ = monotonic_clock::min_time;
2033
2034 ScheduleTimestamp();
2035}
2036
2037LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002038 const Channel *channel, const Connection *connection) {
2039 message_bridge::ChannelTimestampFinder finder(event_loop_);
2040 // Look at any pre-created channel/connection pairs.
2041 {
2042 auto it =
2043 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2044 if (it != channel_timestamp_loggers_.end()) {
2045 return it->second.get();
2046 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002047 }
2048
Austin Schuh61e973f2021-02-21 21:43:56 -08002049 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2050 // to.
2051 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2052
2053 {
2054 // See if that has been created before. If so, cache it in
2055 // channel_timestamp_loggers_ and return.
2056 auto it = timestamp_loggers_.find(timestamp_channel);
2057 if (it != timestamp_loggers_.end()) {
2058 CHECK(channel_timestamp_loggers_
2059 .try_emplace(std::make_pair(channel, connection), it->second)
2060 .second);
2061 return it->second.get();
2062 }
2063 }
2064
2065 // Otherwise, make a sender, save it, and cache it.
2066 auto result = channel_timestamp_loggers_.try_emplace(
2067 std::make_pair(channel, connection),
2068 std::make_shared<RemoteMessageSender>(
2069 event_loop()->MakeSender<RemoteMessage>(
2070 timestamp_channel->name()->string_view()),
2071 event_loop()));
2072
2073 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2074 .second);
2075 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002076}
2077
Austin Schuhdda74ec2021-01-03 19:30:37 -08002078TimestampedMessage LogReader::State::PopOldest() {
James Kuszmaula16a7912022-06-17 10:58:12 -07002079 if (message_queuer_.has_value()) {
2080 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2081 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2082 message_queuer_->SetState(
2083 message.value().monotonic_event_time +
2084 std::chrono::duration_cast<std::chrono::nanoseconds>(
2085 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2086 return message.value();
2087 } else {
2088 CHECK(timestamp_mapper_ != nullptr);
2089 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2090 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002091
James Kuszmaula16a7912022-06-17 10:58:12 -07002092 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002093
James Kuszmaula16a7912022-06-17 10:58:12 -07002094 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2095 << result.monotonic_event_time;
2096 timestamp_mapper_->PopFront();
2097 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002098
James Kuszmaula16a7912022-06-17 10:58:12 -07002099 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002100
James Kuszmaula16a7912022-06-17 10:58:12 -07002101 VLOG(1) << "Popped " << result
2102 << configuration::CleanedChannelToString(
2103 event_loop_->configuration()->channels()->Get(
2104 factory_channel_index_[result.channel_index]));
2105 return result;
2106 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002107}
2108
James Kuszmaula16a7912022-06-17 10:58:12 -07002109BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2110 if (!message_queuer_.has_value()) {
2111 return SingleThreadedOldestMessageTime();
2112 }
2113 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2114 if (!message.has_value()) {
2115 return BootTimestamp::max_time();
2116 }
2117 if (message.value().monotonic_event_time.boot == boot_count()) {
2118 ObserveNextMessage(message.value().monotonic_event_time.time,
2119 message.value().realtime_event_time);
2120 }
2121 return message.value().monotonic_event_time;
2122}
2123
2124BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2125 CHECK(!message_queuer_.has_value())
2126 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2127 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002128 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002129 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002130 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002131 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2132 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002133 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002134 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002135 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002136 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002137 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2138 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2139 result_ptr->realtime_event_time);
2140 }
Austin Schuh58646e22021-08-23 23:51:46 -07002141 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002142}
2143
2144void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002145 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002146
Austin Schuhe639ea12021-01-25 13:00:22 -08002147 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2148 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002149}
2150
2151void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002152 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002153 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002154 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002155 for (size_t i = 0; i < channels_.size(); ++i) {
2156 channels_[i].reset();
2157 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002158 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002159 channel_timestamp_loggers_.clear();
2160 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002161 event_loop_unique_ptr_.reset();
2162 event_loop_ = nullptr;
2163 timer_handler_ = nullptr;
2164 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002165 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002166}
2167
Austin Schuhe33c08d2022-02-03 18:15:21 -08002168void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2169 if (start_time != realtime_clock::min_time) {
2170 start_event_notifier_ = std::make_unique<EventNotifier>(
2171 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2172 }
2173}
2174
2175void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2176 if (end_time != realtime_clock::max_time) {
2177 end_event_notifier_ = std::make_unique<EventNotifier>(
2178 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2179 }
2180}
2181
2182void LogReader::State::ObserveNextMessage(
2183 monotonic_clock::time_point monotonic_event,
2184 realtime_clock::time_point realtime_event) {
2185 if (start_event_notifier_) {
2186 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2187 }
2188 if (end_event_notifier_) {
2189 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2190 }
2191}
2192
2193void LogReader::State::ClearTimeFlags() {
2194 start_event_notifier_.reset();
2195 end_event_notifier_.reset();
2196}
2197
2198void LogReader::State::NotifyLogfileStart() {
2199 if (start_event_notifier_) {
2200 if (start_event_notifier_->realtime_event_time() >
2201 realtime_start_time(boot_count())) {
2202 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2203 << " > " << realtime_start_time(boot_count());
2204 return;
2205 }
2206 }
2207 if (found_last_message_) {
2208 VLOG(1) << "Last message already found, bailing";
2209 return;
2210 }
2211 RunOnStart();
2212}
2213
2214void LogReader::State::NotifyFlagStart() {
2215 if (start_event_notifier_->realtime_event_time() >=
2216 realtime_start_time(boot_count())) {
2217 RunOnStart();
2218 }
2219}
2220
2221void LogReader::State::NotifyLogfileEnd() {
2222 if (found_last_message_) {
2223 return;
2224 }
2225
2226 if (!stopped_ && started_) {
2227 RunOnEnd();
2228 }
2229}
2230
2231void LogReader::State::NotifyFlagEnd() {
2232 if (!stopped_ && started_) {
2233 RunOnEnd();
2234 SetFoundLastMessage(true);
2235 }
2236}
2237
James Kuszmaul09632422022-05-25 15:56:19 -07002238void LogReader::State::SetClockOffset() {
2239 if (node_event_loop_factory_ == nullptr) {
2240 // If not running with simulated event loop, set the monotonic clock
2241 // offset.
2242 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2243
2244 if (start_event_notifier_) {
2245 start_event_notifier_->SetClockOffset(clock_offset_);
2246 }
2247 if (end_event_notifier_) {
2248 end_event_notifier_->SetClockOffset(clock_offset_);
2249 }
2250 }
2251}
2252
James Kuszmaulb67409b2022-06-20 16:25:03 -07002253void LogReader::SetRealtimeReplayRate(double replay_rate) {
2254 CHECK(event_loop_factory_ != nullptr)
2255 << ": Can't set replay rate without an event loop factory (have you "
2256 "called Register()?).";
2257 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2258}
2259
Austin Schuhe309d2a2019-11-29 13:25:21 -08002260} // namespace logger
2261} // namespace aos