blob: f80f28de60925b0e24450d7787aeae36efdffdbd [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) {
James Kuszmaul53da7f32022-09-11 11:11:55 -0700291 // If for some reason a timestamp channel is not NOT_LOGGED (which
292 // is unusual), then remap the channel so that the replayed channel
293 // doesn't overlap with the special separate replay we do for
294 // timestamps.
Austin Schuh61e973f2021-02-21 21:43:56 -0800295 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
296 RemapLoggedChannel<RemoteMessage>(
297 timestamp_channel->name()->string_view(), node);
298 }
299 continue;
300 }
301
302 // Otherwise collect this one up as a node to look for a combined
303 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700304 LOG(WARNING) << "Failed to find channel "
305 << finder.SplitChannelName(channel, connection)
306 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800307 remote_nodes.insert(connection->name()->string_view());
308 }
309 }
310 }
311
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700312 std::vector<const Node *> timestamp_logger_nodes =
313 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800314 for (const std::string_view remote_node : remote_nodes) {
315 const std::string channel = finder.CombinedChannelName(remote_node);
316
Austin Schuh0de30f32020-12-06 12:44:28 -0800317 // See if the log file is an old log with MessageHeader channels in it, or
318 // a newer log with RemoteMessage. If we find an older log, rename the
319 // type too along with the name.
320 if (HasChannel<MessageHeader>(channel, node)) {
321 CHECK(!HasChannel<RemoteMessage>(channel, node))
322 << ": Can't have both a MessageHeader and RemoteMessage remote "
323 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800324 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
325 // careful about updating the config, but there are fewer and fewer logs
326 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800327 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
328 "aos.message_bridge.RemoteMessage");
329 } else {
330 CHECK(HasChannel<RemoteMessage>(channel, node))
331 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
332 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
333 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800334 // Only bother to remap if there's something on the channel. We can
335 // tell if the channel was marked NOT_LOGGED or not. This makes the
336 // config not change un-necesarily when we replay a log with NOT_LOGGED
337 // messages.
338 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
339 RemapLoggedChannel<RemoteMessage>(channel, node);
340 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800341 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700342 }
343 }
344
Austin Schuh6aa77be2020-02-22 21:06:40 -0800345 if (replay_configuration) {
346 CHECK_EQ(configuration::MultiNode(configuration()),
347 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700348 << ": Log file and replay config need to both be multi or single "
349 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800350 }
351
Austin Schuh6f3babe2020-01-26 20:34:50 -0800352 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700353 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800354 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800355 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700356 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800357 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 << ": Log file and replay config need to have matching nodes "
359 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700360 for (const Node *node : *logged_configuration()->nodes()) {
361 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700362 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
363 << " in logged config that is not present in the replay "
364 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700365 }
366 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800367 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800368 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800369 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800370}
371
Austin Schuh6aa77be2020-02-22 21:06:40 -0800372LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700373 if (event_loop_factory_unique_ptr_) {
374 Deregister();
375 } else if (event_loop_factory_ != nullptr) {
376 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
377 "is destroyed";
378 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700379 // Zero out some buffers. It's easy to do use-after-frees on these, so make
380 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700381 if (remapped_configuration_buffer_) {
382 remapped_configuration_buffer_->Wipe();
383 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800384}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800385
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800386const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800387 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800388}
389
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800390const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800391 return remapped_configuration_;
392}
393
Austin Schuh07676622021-01-21 18:59:17 -0800394std::vector<const Node *> LogReader::LoggedNodes() const {
395 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800396}
Austin Schuh15649d62019-12-28 16:36:38 -0800397
Austin Schuh11d43732020-09-21 17:28:30 -0700398monotonic_clock::time_point LogReader::monotonic_start_time(
399 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800400 State *state =
401 states_[configuration::GetNodeIndex(configuration(), node)].get();
402 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
403
Austin Schuhf665eb42022-02-03 18:26:25 -0800404 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800405}
406
Austin Schuh11d43732020-09-21 17:28:30 -0700407realtime_clock::time_point LogReader::realtime_start_time(
408 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800409 State *state =
410 states_[configuration::GetNodeIndex(configuration(), node)].get();
411 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
412
Austin Schuhf665eb42022-02-03 18:26:25 -0800413 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800414}
415
Austin Schuh58646e22021-08-23 23:51:46 -0700416void LogReader::OnStart(std::function<void()> fn) {
417 CHECK(!configuration::MultiNode(configuration()));
418 OnStart(nullptr, std::move(fn));
419}
420
421void LogReader::OnStart(const Node *node, std::function<void()> fn) {
422 const int node_index = configuration::GetNodeIndex(configuration(), node);
423 CHECK_GE(node_index, 0);
424 CHECK_LT(node_index, static_cast<int>(states_.size()));
425 State *state = states_[node_index].get();
426 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
427
428 state->OnStart(std::move(fn));
429}
430
James Kuszmaula16a7912022-06-17 10:58:12 -0700431void LogReader::State::QueueThreadUntil(BootTimestamp time) {
432 if (threading_ == ThreadedBuffering::kYes) {
433 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
434 message_queuer_.emplace(
435 [this](const BootTimestamp queue_until) {
436 // This will be called whenever anything prompts us for any state
437 // change; there may be wakeups that result in us not having any new
438 // data to push (even if we aren't done), in which case we will return
439 // nullopt but not done().
440 if (last_queued_message_.has_value() &&
441 queue_until < last_queued_message_) {
442 return util::ThreadedQueue<TimestampedMessage,
443 BootTimestamp>::PushResult{
444 std::nullopt, false,
445 last_queued_message_ == BootTimestamp::max_time()};
446 }
447 TimestampedMessage *message = timestamp_mapper_->Front();
448 // Upon reaching the end of the log, exit.
449 if (message == nullptr) {
450 last_queued_message_ = BootTimestamp::max_time();
451 return util::ThreadedQueue<TimestampedMessage,
452 BootTimestamp>::PushResult{std::nullopt,
453 false, true};
454 }
455 last_queued_message_ = message->monotonic_event_time;
456 const util::ThreadedQueue<TimestampedMessage,
457 BootTimestamp>::PushResult result{
458 *message, queue_until >= last_queued_message_, false};
459 timestamp_mapper_->PopFront();
460 SeedSortedMessages();
461 return result;
462 },
463 time);
464 // Spin until the first few seconds of messages are queued up so that we
465 // don't end up with delays/inconsistent timing during the first few seconds
466 // of replay.
467 message_queuer_->WaitForNoMoreWork();
468 }
469}
470
Austin Schuh58646e22021-08-23 23:51:46 -0700471void LogReader::State::OnStart(std::function<void()> fn) {
472 on_starts_.emplace_back(std::move(fn));
473}
474
475void LogReader::State::RunOnStart() {
476 SetRealtimeOffset(monotonic_start_time(boot_count()),
477 realtime_start_time(boot_count()));
478
479 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
480 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800481 auto fn = [this]() {
482 for (size_t i = 0; i < on_starts_.size(); ++i) {
483 on_starts_[i]();
484 }
485 };
486 if (event_loop_factory_) {
487 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
488 } else {
489 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700490 }
491 stopped_ = false;
492 started_ = true;
493}
494
495void LogReader::OnEnd(std::function<void()> fn) {
496 CHECK(!configuration::MultiNode(configuration()));
497 OnEnd(nullptr, std::move(fn));
498}
499
500void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
501 const int node_index = configuration::GetNodeIndex(configuration(), node);
502 CHECK_GE(node_index, 0);
503 CHECK_LT(node_index, static_cast<int>(states_.size()));
504 State *state = states_[node_index].get();
505 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
506
507 state->OnEnd(std::move(fn));
508}
509
510void LogReader::State::OnEnd(std::function<void()> fn) {
511 on_ends_.emplace_back(std::move(fn));
512}
513
514void LogReader::State::RunOnEnd() {
515 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
516 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800517 auto fn = [this]() {
518 for (size_t i = 0; i < on_ends_.size(); ++i) {
519 on_ends_[i]();
520 }
521 };
522 if (event_loop_factory_) {
523 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
524 } else {
525 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700526 }
527
528 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800529 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700530 if (message_queuer_.has_value()) {
531 message_queuer_->StopPushing();
532 }
Austin Schuh58646e22021-08-23 23:51:46 -0700533}
534
James Kuszmaul94ca5132022-07-19 09:11:08 -0700535std::vector<
536 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
537LogReader::State::NonExclusiveChannels() {
538 CHECK_NOTNULL(node_event_loop_factory_);
539 const aos::Configuration *config = node_event_loop_factory_->configuration();
540 std::vector<
541 std::pair<const aos::Channel *, NodeEventLoopFactory::ExclusiveSenders>>
542 result{// Timing reports can be sent by logged and replayed applications.
543 {aos::configuration::GetChannel(config, "/aos",
544 "aos.timing.Report", "", node_),
545 NodeEventLoopFactory::ExclusiveSenders::kNo},
546 // AOS_LOG may be used in the log and in replay.
547 {aos::configuration::GetChannel(
548 config, "/aos", "aos.logging.LogMessageFbs", "", node_),
549 NodeEventLoopFactory::ExclusiveSenders::kNo}};
550 for (const Node *const node : configuration::GetNodes(config)) {
551 if (node == nullptr) {
552 break;
553 }
554 const Channel *const old_timestamp_channel = aos::configuration::GetChannel(
555 config,
556 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
James Kuszmaula90f3242022-08-03 13:39:59 -0700557 "aos.message_bridge.RemoteMessage", "", node_, /*quiet=*/true);
James Kuszmaul94ca5132022-07-19 09:11:08 -0700558 // The old-style remote timestamp channel can be populated from any
559 // channel, simulated or replayed.
560 if (old_timestamp_channel != nullptr) {
561 result.push_back(std::make_pair(
562 old_timestamp_channel, NodeEventLoopFactory::ExclusiveSenders::kNo));
563 }
564 }
565 // Remove any channels that weren't found due to not existing in the
566 // config.
567 for (size_t ii = 0; ii < result.size();) {
568 if (result[ii].first == nullptr) {
569 result.erase(result.begin() + ii);
570 } else {
571 ++ii;
572 }
573 }
574 return result;
575}
576
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800577void LogReader::Register() {
578 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800579 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800580 Register(event_loop_factory_unique_ptr_.get());
581}
582
Austin Schuh58646e22021-08-23 23:51:46 -0700583void LogReader::RegisterWithoutStarting(
584 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800585 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700586 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800587 filters_ =
588 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800589 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700590 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800591 chrono::duration_cast<chrono::nanoseconds>(
592 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800593
Austin Schuhe639ea12021-01-25 13:00:22 -0800594 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700595 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800596 const size_t node_index =
597 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800598 std::vector<LogParts> filtered_parts = FilterPartsForNode(
599 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800600
James Kuszmaula16a7912022-06-17 10:58:12 -0700601 // We don't run with threading on the buffering for simulated event loops
602 // because we haven't attempted to validate how the interactions beteen the
603 // buffering and the timestamp mapper works when running multiple nodes
604 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800605 states_[node_index] = std::make_unique<State>(
606 filtered_parts.size() == 0u
607 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700608 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700609 filters_.get(), node, State::ThreadedBuffering::kNo);
Austin Schuh8bd96322020-02-13 21:18:22 -0800610 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700611 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800612 event_loop_factory_->GetNodeEventLoopFactory(node),
613 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700614
615 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800616 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800617 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800618 filters_->SetTimestampMappers(std::move(timestamp_mappers));
619
620 // Note: this needs to be set before any times are pulled, or we won't observe
621 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800622 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700623
Austin Schuh287d43d2020-12-04 20:19:33 -0800624 for (const Node *node : configuration::GetNodes(configuration())) {
625 const size_t node_index =
626 configuration::GetNodeIndex(configuration(), node);
627 State *state = states_[node_index].get();
628 for (const Node *other_node : configuration::GetNodes(configuration())) {
629 const size_t other_node_index =
630 configuration::GetNodeIndex(configuration(), other_node);
631 State *other_state = states_[other_node_index].get();
632 if (other_state != state) {
633 state->AddPeer(other_state);
634 }
635 }
636 }
637
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700638 // Register after making all the State objects so we can build references
639 // between them.
640 for (const Node *node : configuration::GetNodes(configuration())) {
641 const size_t node_index =
642 configuration::GetNodeIndex(configuration(), node);
643 State *state = states_[node_index].get();
644
Austin Schuh58646e22021-08-23 23:51:46 -0700645 // If we didn't find any log files with data in them, we won't ever get a
646 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700647 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700648 continue;
649 }
650 ++live_nodes_;
651
652 NodeEventLoopFactory *node_factory =
653 event_loop_factory_->GetNodeEventLoopFactory(node);
654 node_factory->OnStartup([this, state, node]() {
655 RegisterDuringStartup(state->MakeEventLoop(), node);
656 });
657 node_factory->OnShutdown([this, state, node]() {
658 RegisterDuringStartup(nullptr, node);
659 state->DestroyEventLoop();
660 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700661 }
662
James Kuszmaul46d82582020-05-09 19:50:09 -0700663 if (live_nodes_ == 0) {
664 LOG(FATAL)
665 << "Don't have logs from any of the nodes in the replay config--are "
666 "you sure that the replay config matches the original config?";
667 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800668
Austin Schuh87dd3832021-01-01 23:07:31 -0800669 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800670
Austin Schuh858c9f32020-08-31 16:56:12 -0700671 for (std::unique_ptr<State> &state : states_) {
672 state->SeedSortedMessages();
673 }
674
Austin Schuh6f3babe2020-01-26 20:34:50 -0800675 // Forwarding is tracked per channel. If it is enabled, we want to turn it
676 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700677 // nodes, and also replayed on the other nodes. This may not satisfy all
678 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800679 if (configuration::MultiNode(event_loop_factory_->configuration())) {
680 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
681 const Channel *channel = logged_configuration()->channels()->Get(i);
682 const Node *node = configuration::GetNode(
683 configuration(), channel->source_node()->string_view());
684
Austin Schuh8bd96322020-02-13 21:18:22 -0800685 State *state =
686 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800687
688 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700689 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800690
691 event_loop_factory_->DisableForwarding(remapped_channel);
692 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700693
694 // If we are replaying a log, we don't want a bunch of redundant messages
695 // from both the real message bridge and simulated message bridge.
James Kuszmaul94ca5132022-07-19 09:11:08 -0700696 event_loop_factory_->PermanentlyDisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800697 }
Austin Schuh891214d2021-11-11 20:35:02 -0800698
699 // Write pseudo start times out to file now that we are all setup.
700 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700701}
702
703void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
704 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800705 StartAfterRegister(event_loop_factory);
706}
707
708void LogReader::StartAfterRegister(
709 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700710 // We want to start the log file at the last start time of the log files
711 // from all the nodes. Compute how long each node's simulation needs to run
712 // to move time to this point.
713 distributed_clock::time_point start_time = distributed_clock::min_time;
714
715 // TODO(austin): We want an "OnStart" callback for each node rather than
716 // running until the last node.
717
718 for (std::unique_ptr<State> &state : states_) {
719 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
720 << " for node " << MaybeNodeName(state->node()) << "now "
721 << state->monotonic_now();
722 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
723 continue;
724 }
725 // And start computing the start time on the distributed clock now that
726 // that works.
727 start_time = std::max(
728 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
729 }
730
731 // TODO(austin): If a node doesn't have a start time, we might not queue
732 // enough. If this happens, we'll explode with a frozen error eventually.
733
734 CHECK_GE(start_time, distributed_clock::epoch())
735 << ": Hmm, we have a node starting before the start of time. Offset "
736 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800737
Austin Schuhcde938c2020-02-02 17:30:07 -0800738 // While we are starting the system up, we might be relying on matching data
739 // to timestamps on log files where the timestamp log file starts before the
740 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800741 {
742 const bool prior_ignore_missing_data = ignore_missing_data_;
743 ignore_missing_data_ = true;
744 VLOG(1) << "Running until " << start_time << " in Register";
745 event_loop_factory_->RunFor(start_time.time_since_epoch());
746 VLOG(1) << "At start time";
747 // Now that we are running for real, missing data means that the log file is
748 // corrupted or went wrong.
749 ignore_missing_data_ = prior_ignore_missing_data;
750 }
Austin Schuh92547522019-12-28 14:33:43 -0800751
Austin Schuh8bd96322020-02-13 21:18:22 -0800752 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700753 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700754 if (state->realtime_start_time(0) != realtime_clock::min_time) {
755 state->SetRealtimeOffset(state->monotonic_start_time(0),
756 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700757 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700758 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
759 << " for node " << MaybeNodeName(state->event_loop()->node())
760 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700761 }
762
763 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800764 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800765 }
766}
767
Austin Schuh2f8fd752020-09-01 22:38:28 -0700768message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800769 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800770 if (filters_) {
771 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800772 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800773 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800774}
775
James Kuszmaul09632422022-05-25 15:56:19 -0700776// TODO(jkuszmaul): Make in-line modifications to
777// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
778// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800779void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700780 filters_ =
781 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
782 event_loop->configuration(), logged_configuration(),
783 log_files_[0].boots, FLAGS_skip_order_validation,
784 chrono::duration_cast<chrono::nanoseconds>(
785 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
786
787 std::vector<TimestampMapper *> timestamp_mappers;
788 for (const Node *node : configuration::GetNodes(configuration())) {
789 const size_t node_index =
790 configuration::GetNodeIndex(configuration(), node);
791 std::vector<LogParts> filtered_parts = FilterPartsForNode(
792 log_files_, node != nullptr ? node->name()->string_view() : "");
793
794 states_[node_index] = std::make_unique<State>(
795 filtered_parts.size() == 0u
796 ? nullptr
797 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700798 filters_.get(), node, State::ThreadedBuffering::kYes);
James Kuszmaul09632422022-05-25 15:56:19 -0700799 State *state = states_[node_index].get();
800
801 state->SetChannelCount(logged_configuration()->channels()->size());
802 timestamp_mappers.emplace_back(state->timestamp_mapper());
803 }
804
805 filters_->SetTimestampMappers(std::move(timestamp_mappers));
806
807 for (const Node *node : configuration::GetNodes(configuration())) {
808 const size_t node_index =
809 configuration::GetNodeIndex(configuration(), node);
810 State *state = states_[node_index].get();
811 for (const Node *other_node : configuration::GetNodes(configuration())) {
812 const size_t other_node_index =
813 configuration::GetNodeIndex(configuration(), other_node);
814 State *other_state = states_[other_node_index].get();
815 if (other_state != state) {
816 state->AddPeer(other_state);
817 }
818 }
819 }
820 for (const Node *node : configuration::GetNodes(configuration())) {
821 if (node == nullptr || node->name()->string_view() ==
822 event_loop->node()->name()->string_view()) {
823 Register(event_loop, event_loop->node());
824 } else {
825 Register(nullptr, node);
826 }
827 }
Austin Schuh58646e22021-08-23 23:51:46 -0700828}
829
830void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800831 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700832 states_[configuration::GetNodeIndex(configuration(), node)].get();
833
834 // If we didn't find any log files with data in them, we won't ever get a
835 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700836 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700837 return;
838 }
James Kuszmaul09632422022-05-25 15:56:19 -0700839
840 if (event_loop != nullptr) {
841 ++live_nodes_;
842 }
Austin Schuh58646e22021-08-23 23:51:46 -0700843
844 if (event_loop_factory_ != nullptr) {
845 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
846 [this, event_loop, node]() {
847 RegisterDuringStartup(event_loop, node);
848 });
849 } else {
850 RegisterDuringStartup(event_loop, node);
851 }
852}
853
854void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700855 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700856 CHECK(event_loop->configuration() == configuration());
857 }
858
859 State *state =
860 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800861
James Kuszmaul09632422022-05-25 15:56:19 -0700862 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800863 state->ClearTimeFlags();
864 }
865
Austin Schuh858c9f32020-08-31 16:56:12 -0700866 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800867
Tyler Chatow67ddb032020-01-12 14:30:04 -0800868 // We don't run timing reports when trying to print out logged data, because
869 // otherwise we would end up printing out the timing reports themselves...
870 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700871 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700872 event_loop->SkipTimingReport();
873 event_loop->SkipAosLog();
874 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800875
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700876 for (size_t logged_channel_index = 0;
877 logged_channel_index < logged_configuration()->channels()->size();
878 ++logged_channel_index) {
879 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700880 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700881 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800882
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700883 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700884 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700885
886 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700887
Austin Schuh58646e22021-08-23 23:51:46 -0700888 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
889 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700890 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700891 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800892
Austin Schuh58646e22021-08-23 23:51:46 -0700893 // We've got a message which is being forwarded to this node.
894 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700895
896 source_state =
897 states_[configuration::GetNodeIndex(configuration(), source_node)]
898 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800899 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700900
Austin Schuh58646e22021-08-23 23:51:46 -0700901 // We are the source, and it is forwarded.
902 const bool is_forwarded =
903 configuration::ChannelIsSendableOnNode(channel, node) &&
904 configuration::ConnectionCount(channel);
905
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700906 state->SetChannel(
907 logged_channel_index,
908 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700909 event_loop && logged &&
910 configuration::ChannelIsReadableOnNode(channel, node)
911 ? event_loop->MakeRawSender(channel)
912 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700913 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700914
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700915 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700916 const Node *source_node = configuration::GetNode(
917 configuration(), channel->source_node()->string_view());
918
919 for (const Connection *connection : *channel->destination_nodes()) {
920 const bool delivery_time_is_logged =
921 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
922 source_node);
923
924 if (delivery_time_is_logged) {
925 State *destination_state =
926 states_[configuration::GetNodeIndex(
927 configuration(), connection->name()->string_view())]
928 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700929 if (destination_state) {
930 destination_state->SetRemoteTimestampSender(
931 logged_channel_index,
932 event_loop ? state->RemoteTimestampSender(channel, connection)
933 : nullptr);
934 }
Austin Schuh58646e22021-08-23 23:51:46 -0700935 }
936 }
937 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800938 }
939
Austin Schuh58646e22021-08-23 23:51:46 -0700940 if (!event_loop) {
941 state->ClearRemoteTimestampSenders();
942 state->set_timer_handler(nullptr);
943 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800944 return;
945 }
946
Austin Schuh858c9f32020-08-31 16:56:12 -0700947 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700948 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800949 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700950 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700951 if (exit_on_finish_ && live_nodes_ == 0 &&
952 event_loop_factory_ != nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -0700953 CHECK_NOTNULL(event_loop_factory_)->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800954 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800955 return;
956 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700957
Austin Schuhdda74ec2021-01-03 19:30:37 -0800958 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700959
960 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
961 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800962
Austin Schuhe309d2a2019-11-29 13:25:21 -0800963 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700964 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700965 if (event_loop_factory_ != nullptr) {
966 // Only enforce exact timing in simulation.
967 if (!FLAGS_skip_order_validation) {
968 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
969 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
970 << monotonic_now << " trying to send "
971 << timestamped_message.monotonic_event_time << " failure "
972 << state->DebugString();
973 } else if (BootTimestamp{.boot = state->boot_count(),
974 .time = monotonic_now} !=
975 timestamped_message.monotonic_event_time) {
976 LOG(WARNING) << "Check failed: monotonic_now == "
977 "timestamped_message.monotonic_event_time) ("
978 << monotonic_now << " vs. "
979 << timestamped_message.monotonic_event_time
980 << "): " << FlatbufferToJson(state->event_loop()->node())
981 << " Now " << monotonic_now << " trying to send "
982 << timestamped_message.monotonic_event_time << " failure "
983 << state->DebugString();
984 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700985 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800986
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700987 if (timestamped_message.monotonic_event_time.time >
988 state->monotonic_start_time(
989 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700990 event_loop_factory_ != nullptr ||
991 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800992 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800993 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -0700994 BootTimestamp::min_time() &&
995 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800996 // Confirm that the message was sent on the sending node before the
997 // destination node (this node). As a proxy, do this by making sure
998 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800999 //
1000 // TODO(austin): <= means that the cause message (which we know) could
1001 // happen after the effect even though we know they are at the same
1002 // time. I doubt anyone will notice for a bit, but we should really
1003 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -07001004 BootTimestamp monotonic_remote_now =
1005 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001006 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -07001007 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -08001008 monotonic_remote_now.boot)
1009 << state->event_loop()->node()->name()->string_view() << " to "
1010 << state->remote_node(timestamped_message.channel_index)
1011 ->name()
1012 ->string_view()
1013 << " while trying to send a message on "
1014 << configuration::CleanedChannelToString(
1015 logged_configuration()->channels()->Get(
1016 timestamped_message.channel_index))
1017 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001018 CHECK_LE(timestamped_message.monotonic_remote_time,
1019 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001020 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001021 << state->remote_node(timestamped_message.channel_index)
1022 ->name()
1023 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001024 << " while trying to send a message on "
1025 << configuration::CleanedChannelToString(
1026 logged_configuration()->channels()->Get(
1027 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001028 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -07001029 } else if (monotonic_remote_now.boot !=
1030 timestamped_message.monotonic_remote_time.boot) {
1031 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
1032 << " vs "
1033 << timestamped_message.monotonic_remote_time.boot;
1034 } else if (timestamped_message.monotonic_remote_time >
1035 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001036 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001037 << "Check failed: timestamped_message.monotonic_remote_time < "
1038 "state->monotonic_remote_now(timestamped_message.channel_"
1039 "index) ("
1040 << timestamped_message.monotonic_remote_time << " vs. "
1041 << state->monotonic_remote_now(
1042 timestamped_message.channel_index)
1043 << ") " << state->event_loop()->node()->name()->string_view()
1044 << " to "
1045 << state->remote_node(timestamped_message.channel_index)
1046 ->name()
1047 ->string_view()
1048 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001049 << " ("
1050 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001051 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001052 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001053 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001054 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001055 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001056 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001057 << ") " << state->DebugString();
1058 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001059 }
1060
Austin Schuh15649d62019-12-28 16:36:38 -08001061 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001062 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001063 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001064
Austin Schuh2f8fd752020-09-01 22:38:28 -07001065 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001066 << timestamped_message.monotonic_event_time << " "
1067 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001068 // TODO(austin): std::move channel_data in and make that efficient in
1069 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001070 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001071 } else if (state->found_last_message() ||
1072 (!ignore_missing_data_ &&
1073 // When starting up, we can have data which was sent before
1074 // the log starts, but the timestamp was after the log
1075 // starts. This is unreasonable to avoid, so ignore the
1076 // missing data.
1077 timestamped_message.monotonic_remote_time.time >=
1078 state->monotonic_remote_start_time(
1079 timestamped_message.monotonic_remote_time.boot,
1080 timestamped_message.channel_index) &&
1081 !FLAGS_skip_missing_forwarding_entries)) {
1082 if (!state->found_last_message()) {
1083 // We've found a timestamp without data that we expect to have data
1084 // for. This likely means that we are at the end of the log file.
1085 // Record it and CHECK that in the rest of the log file, we don't find
1086 // any more data on that channel. Not all channels will end at the
1087 // same point in time since they can be in different files.
1088 VLOG(1) << "Found the last message on channel "
1089 << timestamped_message.channel_index << ", "
1090 << configuration::CleanedChannelToString(
1091 logged_configuration()->channels()->Get(
1092 timestamped_message.channel_index))
1093 << " on node " << MaybeNodeName(state->event_loop()->node())
1094 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001095
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001096 // The user might be working with log files from 1 node but forgot to
1097 // configure the infrastructure to log data for a remote channel on
1098 // that node. That can be very hard to debug, even though the log
1099 // reader is doing the right thing. At least log a warning in that
1100 // case and tell the user what is happening so they can either update
1101 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001102 const std::vector<std::string> logger_nodes =
1103 FindLoggerNodes(log_files_);
1104 if (logger_nodes.size()) {
1105 // We have old logs which don't have the logger nodes logged. In
1106 // that case, we can't be helpful :(
1107 bool data_logged = false;
1108 const Channel *channel = logged_configuration()->channels()->Get(
1109 timestamped_message.channel_index);
1110 for (const std::string &node : logger_nodes) {
1111 data_logged |=
1112 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1113 }
1114 if (!data_logged) {
1115 LOG(WARNING) << "Got a timestamp without any logfiles which "
1116 "could contain data for channel "
1117 << configuration::CleanedChannelToString(channel);
1118 LOG(WARNING) << "Only have logs logged on ["
1119 << absl::StrJoin(logger_nodes, ", ") << "]";
1120 LOG(WARNING)
1121 << "Dropping the rest of the data on "
1122 << state->event_loop()->node()->name()->string_view();
1123 LOG(WARNING)
1124 << "Consider using --skip_missing_forwarding_entries to "
1125 "bypass this, update your config to log it, or add data "
1126 "from one of the nodes it is logged on.";
1127 }
1128 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001129 // Now that we found the end of one channel, artificially stop the
1130 // rest by setting the found_last_message bit. It is confusing when
1131 // part of your data gets replayed but not all. The rest of them will
1132 // get dropped as they are replayed to keep memory usage down.
1133 state->SetFoundLastMessage(true);
1134
1135 // Vector storing if we've seen a nullptr message or not per channel.
1136 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001137 }
1138
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001139 // Make sure that once we have seen the last message on a channel,
1140 // data doesn't start back up again. If the user wants to play
1141 // through events like this, they can set
1142 // --skip_missing_forwarding_entries or ignore_missing_data_.
1143 if (timestamped_message.data == nullptr) {
1144 state->set_last_message(timestamped_message.channel_index);
1145 } else {
1146 if (state->last_message(timestamped_message.channel_index)) {
1147 LOG(FATAL) << "Found missing data in the middle of the log file on "
1148 "channel "
1149 << timestamped_message.channel_index << " "
1150 << configuration::StrippedChannelToString(
1151 logged_configuration()->channels()->Get(
1152 timestamped_message.channel_index))
1153 << " " << timestamped_message << " "
1154 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001155 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001156 }
Austin Schuh92547522019-12-28 14:33:43 -08001157 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001158 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001159 LOG(WARNING)
1160 << "Not sending data from before the start of the log file. "
1161 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1162 .count()
1163 << " start "
1164 << monotonic_start_time(state->node()).time_since_epoch().count()
1165 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001166 }
1167
James Kuszmaula16a7912022-06-17 10:58:12 -07001168 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001169 if (next_time != BootTimestamp::max_time()) {
1170 if (next_time.boot != state->boot_count()) {
1171 VLOG(1) << "Next message for "
1172 << MaybeNodeName(state->event_loop()->node())
1173 << "is on the next boot, " << next_time << " now is "
1174 << state->monotonic_now();
1175 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001176 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001177 return;
1178 }
James Kuszmaul09632422022-05-25 15:56:19 -07001179 if (event_loop_factory_ != nullptr) {
1180 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1181 << "wakeup for " << next_time.time << "("
1182 << state->ToDistributedClock(next_time.time)
1183 << " distributed), now is " << state->monotonic_now();
1184 } else {
1185 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1186 << "wakeup for " << next_time.time << ", now is "
1187 << state->monotonic_now();
1188 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001189 // TODO(james): This can result in negative times getting passed-through
1190 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001191 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001192 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001193 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1194 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001195 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001196 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001197 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001198 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001199 // Doesn't apply to single-EventLoop replay since the watchers in question
1200 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001201 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001202 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1203 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001204 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001205 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001206
Austin Schuh2f8fd752020-09-01 22:38:28 -07001207 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1208 << state->event_loop()->context().monotonic_event_time << " now "
1209 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001210 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001211
James Kuszmaula16a7912022-06-17 10:58:12 -07001212 state->SeedSortedMessages();
1213
1214 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001215 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001216 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1217 if (start_time_ != realtime_clock::min_time) {
1218 state->SetStartTimeFlag(start_time_);
1219 }
1220 if (end_time_ != realtime_clock::max_time) {
1221 state->SetEndTimeFlag(end_time_);
1222 }
Austin Schuh58646e22021-08-23 23:51:46 -07001223 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001224 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001225 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001226 // Queue up messages and then set clock offsets (we don't want to set
1227 // clock offsets before we've done the work of getting the first messages
1228 // primed).
1229 state->QueueThreadUntil(
1230 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1231 std::chrono::duration<double>(
1232 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaulc3f34d12022-08-15 15:57:55 -07001233 state->MaybeSetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001234 state->Setup(next_time.time);
1235 state->SetupStartupTimer();
1236 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001237 }
1238}
1239
Austin Schuhe33c08d2022-02-03 18:15:21 -08001240void LogReader::SetEndTime(std::string end_time) {
1241 if (end_time.empty()) {
1242 SetEndTime(realtime_clock::max_time);
1243 } else {
1244 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1245 aos::realtime_clock::FromString(end_time);
1246 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1247 << "'. Expected a date in the format of "
1248 "2021-01-15_15-30-35.000000000.";
1249 SetEndTime(*parsed_end_time);
1250 }
1251}
1252
1253void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1254 end_time_ = end_time;
1255}
1256
1257void LogReader::SetStartTime(std::string start_time) {
1258 if (start_time.empty()) {
1259 SetStartTime(realtime_clock::min_time);
1260 } else {
1261 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1262 aos::realtime_clock::FromString(start_time);
1263 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1264 << "'. Expected a date in the format of "
1265 "2021-01-15_15-30-35.000000000.";
1266 SetStartTime(*parsed_start_time);
1267 }
1268}
1269
1270void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1271 start_time_ = start_time;
1272}
1273
Austin Schuhe309d2a2019-11-29 13:25:21 -08001274void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001275 // Make sure that things get destroyed in the correct order, rather than
1276 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001277 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001278 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001279 }
Austin Schuh92547522019-12-28 14:33:43 -08001280
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001281 event_loop_factory_unique_ptr_.reset();
1282 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001283}
1284
James Kuszmaul53da7f32022-09-11 11:11:55 -07001285namespace {
1286// Checks if the specified channel name/type exists in the config and, depending
1287// on the value of conflict_handling, calls conflict_handler or just dies.
1288template <typename F>
1289void CheckAndHandleRemapConflict(std::string_view new_name,
1290 std::string_view new_type,
1291 const Configuration *config,
1292 LogReader::RemapConflict conflict_handling,
1293 F conflict_handler) {
1294 const Channel *existing_channel =
1295 configuration::GetChannel(config, new_name, new_type, "", nullptr, true);
1296 if (existing_channel != nullptr) {
1297 switch (conflict_handling) {
1298 case LogReader::RemapConflict::kDisallow:
1299 LOG(FATAL)
1300 << "Channel "
1301 << configuration::StrippedChannelToString(existing_channel)
1302 << " is already used--you can't remap a logged channel to it.";
1303 break;
1304 case LogReader::RemapConflict::kCascade:
1305 LOG(INFO) << "Automatically remapping "
1306 << configuration::StrippedChannelToString(existing_channel)
1307 << " to avoid conflicts.";
1308 conflict_handler();
1309 break;
1310 }
1311 }
1312}
1313} // namespace
1314
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001315void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001316 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001317 std::string_view new_type,
1318 RemapConflict conflict_handling) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001319 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1320 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1321 if (channel->name()->str() == name &&
1322 channel->type()->string_view() == type) {
1323 CHECK_EQ(0u, remapped_channels_.count(ii))
1324 << "Already remapped channel "
1325 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001326 RemappedChannel remapped_channel;
1327 remapped_channel.remapped_name =
1328 std::string(add_prefix) + std::string(name);
1329 remapped_channel.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001330 const std::string_view remapped_type =
1331 remapped_channel.new_type.empty() ? type : remapped_channel.new_type;
1332 CheckAndHandleRemapConflict(
1333 remapped_channel.remapped_name, remapped_type,
1334 remapped_configuration_, conflict_handling,
1335 [this, &remapped_channel, remapped_type, add_prefix,
1336 conflict_handling]() {
1337 RemapLoggedChannel(remapped_channel.remapped_name, remapped_type,
1338 add_prefix, "", conflict_handling);
1339 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001340 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001341 VLOG(1) << "Remapping channel "
1342 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001343 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001344 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001345 return;
1346 }
1347 }
1348 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1349 << type;
1350}
1351
Austin Schuh01b4c352020-09-21 23:09:39 -07001352void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1353 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001354 std::string_view add_prefix,
James Kuszmaul53da7f32022-09-11 11:11:55 -07001355 std::string_view new_type,
1356 RemapConflict conflict_handling) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001357 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1358 const Channel *remapped_channel =
1359 configuration::GetChannel(logged_configuration(), name, type, "", node);
1360 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1361 << "\", \"type\": \"" << type << "\"}";
1362 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1363 << "\"}";
1364 VLOG(1) << "Remapped "
1365 << aos::configuration::StrippedChannelToString(remapped_channel);
1366
1367 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1368 // we want it to degrade if the heuristics fail to just work.
1369 //
1370 // The easiest way to do this is going to be incredibly specific and verbose.
1371 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1372 // /original/0/spray. Then, create a map from /original/spray to
1373 // /original/0/spray for just the type we were asked for.
1374 if (name != remapped_channel->name()->string_view()) {
1375 MapT new_map;
1376 new_map.match = std::make_unique<ChannelT>();
1377 new_map.match->name = absl::StrCat(add_prefix, name);
1378 new_map.match->type = type;
1379 if (node != nullptr) {
1380 new_map.match->source_node = node->name()->str();
1381 }
1382 new_map.rename = std::make_unique<ChannelT>();
1383 new_map.rename->name =
1384 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1385 maps_.emplace_back(std::move(new_map));
1386 }
1387
1388 const size_t channel_index =
1389 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1390 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1391 << "Already remapped channel "
1392 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001393
1394 RemappedChannel remapped_channel_struct;
1395 remapped_channel_struct.remapped_name =
1396 std::string(add_prefix) +
1397 std::string(remapped_channel->name()->string_view());
1398 remapped_channel_struct.new_type = new_type;
James Kuszmaul53da7f32022-09-11 11:11:55 -07001399 const std::string_view remapped_type = new_type.empty() ? type : new_type;
1400 CheckAndHandleRemapConflict(
1401 remapped_channel_struct.remapped_name, remapped_type,
1402 remapped_configuration_, conflict_handling,
1403 [this, &remapped_channel_struct, remapped_type, node, add_prefix,
1404 conflict_handling]() {
1405 RemapLoggedChannel(remapped_channel_struct.remapped_name, remapped_type,
1406 node, add_prefix, "", conflict_handling);
1407 });
Austin Schuh0de30f32020-12-06 12:44:28 -08001408 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001409 MakeRemappedConfig();
1410}
1411
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001412void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001413 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001414 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001415 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001416 << ": Can't change the mapping after the events are scheduled.";
1417 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001418 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001419
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001420 // If no remapping occurred and we are using the original config, then there
1421 // is nothing interesting to do here.
1422 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001423 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001424 return;
1425 }
1426 // Config to copy Channel definitions from. Use the specified
1427 // replay_configuration_ if it has been provided.
1428 const Configuration *const base_config = replay_configuration_ == nullptr
1429 ? logged_configuration()
1430 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001431
1432 // Create a config with all the channels, but un-sorted/merged. Collect up
1433 // the schemas while we do this. Call MergeConfiguration to sort everything,
1434 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001435
1436 // This is the builder that we use for the config containing all the new
1437 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001438 flatbuffers::FlatBufferBuilder fbb;
1439 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001440 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001441
1442 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1443 << ": Merging logic needs to be updated when the number of channel "
1444 "fields changes.";
1445
1446 // List of schemas.
1447 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1448 // Make sure our new RemoteMessage schema is in there for old logs without it.
1449 schema_map.insert(std::make_pair(
1450 RemoteMessage::GetFullyQualifiedName(),
1451 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1452 message_bridge::RemoteMessageSchema()))));
1453
1454 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001455 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001456 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001457 base_config, logged_configuration()->channels()->Get(pair.first), "",
1458 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001459 channel_offsets.emplace_back(
1460 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001461
1462 if (c->has_destination_nodes()) {
1463 for (const Connection *connection : *c->destination_nodes()) {
1464 switch (connection->timestamp_logger()) {
1465 case LoggerConfig::LOCAL_LOGGER:
1466 case LoggerConfig::NOT_LOGGED:
1467 // There is no timestamp channel associated with this, so ignore it.
1468 break;
1469
1470 case LoggerConfig::REMOTE_LOGGER:
1471 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1472 // We want to make a split timestamp channel regardless of what type
1473 // of log this used to be. No sense propagating the single
1474 // timestamp channel.
1475
1476 CHECK(connection->has_timestamp_logger_nodes());
1477 for (const flatbuffers::String *timestamp_logger_node :
1478 *connection->timestamp_logger_nodes()) {
1479 const Node *node = configuration::GetNode(
1480 logged_configuration(), timestamp_logger_node->string_view());
1481 message_bridge::ChannelTimestampFinder finder(
1482 logged_configuration(), "log_reader", node);
1483
1484 // We are assuming here that all the maps are setup correctly to
1485 // handle arbitrary timestamps. Apply the maps for this node to
1486 // see what name this ends up with.
1487 std::string name = finder.SplitChannelName(
1488 pair.second.remapped_name, c->type()->str(), connection);
1489 std::string unmapped_name = name;
1490 configuration::HandleMaps(logged_configuration()->maps(), &name,
1491 "aos.message_bridge.RemoteMessage",
1492 node);
1493 CHECK_NE(name, unmapped_name)
1494 << ": Remote timestamp channel was not remapped, this is "
1495 "very fishy";
1496 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1497 fbb.CreateString(name);
1498 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1499 fbb.CreateString("aos.message_bridge.RemoteMessage");
1500 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1501 fbb.CreateString(timestamp_logger_node->string_view());
1502
1503 // Now, build a channel. Don't log it, 2 senders, and match the
1504 // source frequency.
1505 Channel::Builder channel_builder(fbb);
1506 channel_builder.add_name(channel_name_offset);
1507 channel_builder.add_type(channel_type_offset);
1508 channel_builder.add_source_node(source_node_offset);
1509 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1510 channel_builder.add_num_senders(2);
1511 if (c->has_frequency()) {
1512 channel_builder.add_frequency(c->frequency());
1513 }
1514 channel_offsets.emplace_back(channel_builder.Finish());
1515 }
1516 break;
1517 }
1518 }
1519 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001520 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001521
Austin Schuh0de30f32020-12-06 12:44:28 -08001522 // Now reconstruct the original channels, translating types as needed
1523 for (const Channel *c : *base_config->channels()) {
1524 // Search for a mapping channel.
1525 std::string_view new_type = "";
1526 for (auto &pair : remapped_channels_) {
1527 const Channel *const remapped_channel =
1528 logged_configuration()->channels()->Get(pair.first);
1529 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1530 remapped_channel->type()->string_view() == c->type()->string_view()) {
1531 new_type = pair.second.new_type;
1532 break;
1533 }
1534 }
1535
1536 // Copy everything over.
1537 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1538
1539 // Add the schema if it doesn't exist.
1540 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1541 CHECK(c->has_schema());
1542 schema_map.insert(std::make_pair(c->type()->string_view(),
1543 RecursiveCopyFlatBuffer(c->schema())));
1544 }
1545 }
1546
1547 // The MergeConfiguration API takes a vector, not a map. Convert.
1548 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1549 while (!schema_map.empty()) {
1550 schemas.emplace_back(std::move(schema_map.begin()->second));
1551 schema_map.erase(schema_map.begin());
1552 }
1553
1554 // Create the Configuration containing the new channels that we want to add.
1555 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1556 channels_offset =
1557 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1558
1559 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001560 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001561 if (base_config->maps()) {
1562 for (const Map *map : *base_config->maps()) {
1563 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1564 }
1565 }
1566
1567 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001568 for (const MapT &map : maps_) {
1569 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001570 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001571 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001572 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001573 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001574 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001575 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1576 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001577 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001578 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001579 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001580 match_builder.add_name(match_name_offset);
1581 match_builder.add_type(match_type_offset);
1582 if (!map.match->source_node.empty()) {
1583 match_builder.add_source_node(match_source_node_offset);
1584 }
1585 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1586
Austin Schuh0de30f32020-12-06 12:44:28 -08001587 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001588 rename_builder.add_name(rename_name_offset);
1589 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1590
Austin Schuh0de30f32020-12-06 12:44:28 -08001591 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001592 map_builder.add_match(match_offset);
1593 map_builder.add_rename(rename_offset);
1594 map_offsets.emplace_back(map_builder.Finish());
1595 }
1596
Austin Schuh0de30f32020-12-06 12:44:28 -08001597 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1598 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001599
Austin Schuh0de30f32020-12-06 12:44:28 -08001600 // And copy everything else over.
1601 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1602 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1603
1604 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1605 applications_offset =
1606 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1607
1608 // Now insert everything else in unmodified.
1609 ConfigurationBuilder configuration_builder(fbb);
1610 if (!channels_offset.IsNull()) {
1611 configuration_builder.add_channels(channels_offset);
1612 }
1613 if (!maps_offsets.IsNull()) {
1614 configuration_builder.add_maps(maps_offsets);
1615 }
1616 if (!nodes_offset.IsNull()) {
1617 configuration_builder.add_nodes(nodes_offset);
1618 }
1619 if (!applications_offset.IsNull()) {
1620 configuration_builder.add_applications(applications_offset);
1621 }
1622
1623 if (base_config->has_channel_storage_duration()) {
1624 configuration_builder.add_channel_storage_duration(
1625 base_config->channel_storage_duration());
1626 }
1627
1628 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1629 << ": Merging logic needs to be updated when the number of configuration "
1630 "fields changes.";
1631
1632 fbb.Finish(configuration_builder.Finish());
1633
1634 // Clean it up and return it! By using MergeConfiguration here, we'll
1635 // actually get a deduplicated config for free too.
1636 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1637 configuration::MergeConfiguration(
1638 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1639
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001640 remapped_configuration_buffer_ =
1641 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001642 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001643
1644 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001645
1646 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001647}
1648
Austin Schuh1c227352021-09-17 12:53:54 -07001649std::vector<const Channel *> LogReader::RemappedChannels() const {
1650 std::vector<const Channel *> result;
1651 result.reserve(remapped_channels_.size());
1652 for (auto &pair : remapped_channels_) {
1653 const Channel *const logged_channel =
1654 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1655
1656 auto channel_iterator = std::lower_bound(
1657 remapped_configuration_->channels()->cbegin(),
1658 remapped_configuration_->channels()->cend(),
1659 std::make_pair(std::string_view(pair.second.remapped_name),
1660 logged_channel->type()->string_view()),
1661 CompareChannels);
1662
1663 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1664 CHECK(EqualsChannels(
1665 *channel_iterator,
1666 std::make_pair(std::string_view(pair.second.remapped_name),
1667 logged_channel->type()->string_view())));
1668 result.push_back(*channel_iterator);
1669 }
1670 return result;
1671}
1672
Austin Schuh6f3babe2020-01-26 20:34:50 -08001673const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001674 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001675 const Channel *channel) {
1676 std::string_view channel_name = channel->name()->string_view();
1677 std::string_view channel_type = channel->type()->string_view();
1678 const int channel_index =
1679 configuration::ChannelIndex(logged_configuration(), channel);
1680 // If the channel is remapped, find the correct channel name to use.
1681 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001682 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001683 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001684 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001685 }
1686
Austin Schuhee711052020-08-24 16:06:09 -07001687 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001688 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001689 configuration(), channel_name, channel_type,
1690 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001691
1692 CHECK(remapped_channel != nullptr)
1693 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1694 << channel_type << "\"} because it is not in the provided configuration.";
1695
1696 return remapped_channel;
1697}
1698
James Kuszmaul09632422022-05-25 15:56:19 -07001699LogReader::State::State(
1700 std::unique_ptr<TimestampMapper> timestamp_mapper,
1701 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaula16a7912022-06-17 10:58:12 -07001702 const Node *node, LogReader::State::ThreadedBuffering threading)
James Kuszmaul09632422022-05-25 15:56:19 -07001703 : timestamp_mapper_(std::move(timestamp_mapper)),
1704 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001705 multinode_filters_(multinode_filters),
1706 threading_(threading) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001707
1708void LogReader::State::AddPeer(State *peer) {
1709 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1710 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1711 }
1712}
Austin Schuh858c9f32020-08-31 16:56:12 -07001713
Austin Schuh58646e22021-08-23 23:51:46 -07001714void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001715 NodeEventLoopFactory *node_event_loop_factory,
1716 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001717 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001718 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001719}
1720
1721void LogReader::State::SetChannelCount(size_t count) {
1722 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001723 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001724 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001725 channel_source_state_.resize(count);
1726 factory_channel_index_.resize(count);
1727 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001728}
1729
Austin Schuh58646e22021-08-23 23:51:46 -07001730void LogReader::State::SetRemoteTimestampSender(
1731 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1732 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1733}
1734
Austin Schuh858c9f32020-08-31 16:56:12 -07001735void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001736 size_t logged_channel_index, size_t factory_channel_index,
1737 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001738 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1739 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001740 channels_[logged_channel_index] = std::move(sender);
1741 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001742 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001743
Austin Schuh58646e22021-08-23 23:51:46 -07001744 if (is_forwarded) {
1745 queue_index_map_[logged_channel_index] =
1746 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001747 }
1748
1749 factory_channel_index_[logged_channel_index] = factory_channel_index;
1750}
1751
James Kuszmaula16a7912022-06-17 10:58:12 -07001752void LogReader::State::TrackMessageSendTiming(
1753 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1754 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1755 return;
1756 }
1757
1758 timing::MessageTimingT sample;
1759 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1760 sender.channel());
1761 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1762 sample.actual_send_time =
1763 sender.monotonic_sent_time().time_since_epoch().count();
1764 sample.send_time_error = aos::time::DurationInSeconds(
1765 expected_send_time - sender.monotonic_sent_time());
1766 send_timings_.push_back(sample);
1767
1768 // Somewhat arbitrarily send out timing information in batches of 100. No need
1769 // to create excessive overhead in regenerated logfiles.
1770 // TODO(james): The overhead may be fine.
1771 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1772 CHECK(timing_statistics_sender_.valid());
1773 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1774 SendMessageTimings();
1775 }
1776}
1777
1778void LogReader::State::SendMessageTimings() {
1779 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1780 return;
1781 }
1782 auto builder = timing_statistics_sender_.MakeBuilder();
1783 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1784 for (const auto &timing : send_timings_) {
1785 timing_offsets.push_back(
1786 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1787 }
1788 send_timings_.clear();
1789 flatbuffers::Offset<
1790 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1791 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1792 timing::ReplayTiming::Builder timing_builder =
1793 builder.MakeBuilder<timing::ReplayTiming>();
1794 timing_builder.add_messages(timings_offset);
1795 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1796}
1797
Austin Schuh287d43d2020-12-04 20:19:33 -08001798bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1799 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001800 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001801 uint32_t remote_queue_index = 0xffffffff;
1802
Austin Schuh287d43d2020-12-04 20:19:33 -08001803 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001804 State *source_state =
1805 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001806 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001807 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001808 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001809
Austin Schuh9942bae2021-01-07 22:06:44 -08001810 struct SentTimestamp {
1811 monotonic_clock::time_point monotonic_event_time;
1812 uint32_t queue_index;
1813 } search;
1814
Austin Schuh58646e22021-08-23 23:51:46 -07001815 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1816 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001817 search.monotonic_event_time =
1818 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001819 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001820
1821 // Find the sent time if available.
1822 auto element = std::lower_bound(
1823 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001824 [](ContiguousSentTimestamp a, SentTimestamp b) {
1825 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001826 return true;
1827 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001828 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001829 return false;
1830 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001831
1832 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001833 return true;
1834 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001835 if (a.starting_queue_index >= b.queue_index) {
1836 return false;
1837 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001838
Austin Schuh9942bae2021-01-07 22:06:44 -08001839 // If it isn't clearly below or above, it is below. Since we return
1840 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001841 return false;
1842 });
1843
1844 // TODO(austin): Be a bit more principled here, but we will want to do that
1845 // after the logger rewrite. We hit this when one node finishes, but the
1846 // other node isn't done yet. So there is no send time, but there is a
1847 // receive time.
1848 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001849 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1850 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001851
1852 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001853 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001854 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001855 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001856 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001857 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001858 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001859 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001860
Austin Schuh58646e22021-08-23 23:51:46 -07001861 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001862 element->actual_queue_index -
1863 element->starting_queue_index;
1864 } else {
1865 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001866 }
Austin Schuh58646e22021-08-23 23:51:46 -07001867 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1868 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001869 }
1870
James Kuszmaul09632422022-05-25 15:56:19 -07001871 if (event_loop_factory_ != nullptr &&
1872 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1873 multinode_filters_ != nullptr) {
1874 // Sanity check that we are using consistent boot uuids.
1875 State *source_state =
1876 channel_source_state_[timestamped_message.channel_index];
1877 CHECK_EQ(multinode_filters_->boot_uuid(
1878 configuration::GetNodeIndex(event_loop_->configuration(),
1879 source_state->node()),
1880 timestamped_message.monotonic_remote_time.boot),
1881 CHECK_NOTNULL(
1882 CHECK_NOTNULL(
1883 channel_source_state_[timestamped_message.channel_index])
1884 ->event_loop_)
1885 ->boot_uuid());
1886 }
1887
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001888 // Send! Use the replayed queue index here instead of the logged queue index
1889 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001890 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001891 RawSender::SharedSpan(timestamped_message.data,
1892 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001893 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001894 timestamped_message.realtime_remote_time, remote_queue_index,
1895 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001896 ? CHECK_NOTNULL(multinode_filters_)
1897 ->boot_uuid(configuration::GetNodeIndex(
1898 event_loop_->configuration(),
1899 channel_source_state_[timestamped_message
1900 .channel_index]
1901 ->node()),
1902 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001903 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001904 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001905 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1906 timestamped_message.monotonic_event_time.time) {
1907 // Only track errors for non-fetched messages.
1908 TrackMessageSendTiming(
1909 *sender,
1910 timestamped_message.monotonic_event_time.time + clock_offset());
1911 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001912
Austin Schuh287d43d2020-12-04 20:19:33 -08001913 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001914 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001915 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1916 // Nothing here, start a range with 0 length.
1917 ContiguousSentTimestamp timestamp;
1918 timestamp.starting_monotonic_event_time =
1919 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001920 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001921 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001922 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001923 timestamp.actual_queue_index = sender->sent_queue_index();
1924 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1925 timestamp);
1926 } else {
1927 // We've got something. See if the next timestamp is still contiguous. If
1928 // so, grow it.
1929 ContiguousSentTimestamp *back =
1930 &queue_index_map_[timestamped_message.channel_index]->back();
1931 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001932 (timestamped_message.queue_index.index -
1933 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001934 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001935 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001936 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001937 } else {
1938 // Otherwise, make a new one.
1939 ContiguousSentTimestamp timestamp;
1940 timestamp.starting_monotonic_event_time =
1941 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001942 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001943 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001944 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001945 timestamp.actual_queue_index = sender->sent_queue_index();
1946 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1947 timestamp);
1948 }
1949 }
1950
1951 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1952 // queue index diverge a couple of elements, which would be a very small
1953 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001954 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1955 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07001956 // TODO(james): Currently, If running replay against a single event loop,
1957 // remote timestamps will not get replayed because this code-path only
1958 // gets triggered on the event loop that receives the forwarded message
1959 // that the timestamps correspond to. This code, as written, also doesn't
1960 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07001961 State *source_state =
1962 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1963
Austin Schuh969cd602021-01-03 00:09:45 -08001964 flatbuffers::FlatBufferBuilder fbb;
1965 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001966 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1967 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001968
Austin Schuh969cd602021-01-03 00:09:45 -08001969 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001970
1971 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001972 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001973
1974 // Swap the remote and sent metrics. They are from the sender's
1975 // perspective, not the receiver's perspective.
1976 message_header_builder.add_monotonic_sent_time(
1977 sender->monotonic_sent_time().time_since_epoch().count());
1978 message_header_builder.add_realtime_sent_time(
1979 sender->realtime_sent_time().time_since_epoch().count());
1980 message_header_builder.add_queue_index(sender->sent_queue_index());
1981
Austin Schuh58646e22021-08-23 23:51:46 -07001982 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1983 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001984 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001985 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1986 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001987 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001988 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001989
1990 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001991 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001992
Austin Schuh969cd602021-01-03 00:09:45 -08001993 fbb.Finish(message_header_builder.Finish());
1994
1995 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1996 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001997 timestamped_message.monotonic_timestamp_time,
1998 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001999 }
2000
2001 return true;
2002}
2003
Austin Schuh969cd602021-01-03 00:09:45 -08002004LogReader::RemoteMessageSender::RemoteMessageSender(
2005 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2006 : event_loop_(event_loop),
2007 sender_(std::move(sender)),
2008 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2009
2010void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2011 if (remote_timestamps_.empty()) {
2012 CHECK_NOTNULL(timer_);
2013 timer_->Disable();
2014 scheduled_time_ = monotonic_clock::min_time;
2015 return;
2016 }
2017
2018 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2019 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002020 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002021 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08002022 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
2023 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002024 }
2025}
2026
2027void LogReader::RemoteMessageSender::Send(
2028 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07002029 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002030 // There are 2 variants of logs.
2031 // 1) Logs without monotonic_timestamp_time
2032 // 2) Logs with monotonic_timestamp_time
2033 //
2034 // As of Jan 2021, we shouldn't have any more logs without
2035 // monotonic_timestamp_time. We don't have data locked up in those logs worth
2036 // the effort of saving.
2037 //
2038 // This gives us 3 cases, 2 of which are undistinguishable.
2039 // 1) Old log without monotonic_timestamp_time.
2040 // 2) New log with monotonic_timestamp_time where the timestamp was logged
2041 // remotely so we actually have monotonic_timestamp_time.
2042 // 3) New log, but the timestamp was logged on the node receiving the message
2043 // so there is no monotonic_timestamp_time.
2044 //
2045 // Our goal when replaying is to accurately reproduce the state of the world
2046 // present when logging. If a timestamp wasn't sent back across the network,
2047 // we shouldn't replay one back across the network.
2048 //
2049 // Given that we don't really care about 1, we can use the presence of the
2050 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
2051 // monotonic_timestamp_time, this means the message was logged locally and
2052 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07002053 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07002054 return;
Austin Schuh969cd602021-01-03 00:09:45 -08002055 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07002056
Austin Schuh58646e22021-08-23 23:51:46 -07002057 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
2058
Austin Schuhc41d6a82021-07-16 14:49:23 -07002059 remote_timestamps_.emplace(
2060 std::upper_bound(
2061 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07002062 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07002063 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2064 const Timestamp &timestamp) {
2065 return monotonic_timestamp_time <
2066 timestamp.monotonic_timestamp_time;
2067 }),
Austin Schuh58646e22021-08-23 23:51:46 -07002068 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07002069 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08002070}
2071
2072void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08002073 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
2074 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08002075 CHECK(!remote_timestamps_.empty());
2076
2077 // Send out all timestamps at the currently scheduled time.
2078 while (remote_timestamps_.front().monotonic_timestamp_time ==
2079 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07002080 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
2081 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08002082 remote_timestamps_.pop_front();
2083 if (remote_timestamps_.empty()) {
2084 break;
2085 }
2086 }
2087 scheduled_time_ = monotonic_clock::min_time;
2088
2089 ScheduleTimestamp();
2090}
2091
2092LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08002093 const Channel *channel, const Connection *connection) {
2094 message_bridge::ChannelTimestampFinder finder(event_loop_);
2095 // Look at any pre-created channel/connection pairs.
2096 {
2097 auto it =
2098 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2099 if (it != channel_timestamp_loggers_.end()) {
2100 return it->second.get();
2101 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002102 }
2103
Austin Schuh61e973f2021-02-21 21:43:56 -08002104 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2105 // to.
2106 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2107
2108 {
2109 // See if that has been created before. If so, cache it in
2110 // channel_timestamp_loggers_ and return.
2111 auto it = timestamp_loggers_.find(timestamp_channel);
2112 if (it != timestamp_loggers_.end()) {
2113 CHECK(channel_timestamp_loggers_
2114 .try_emplace(std::make_pair(channel, connection), it->second)
2115 .second);
2116 return it->second.get();
2117 }
2118 }
2119
2120 // Otherwise, make a sender, save it, and cache it.
2121 auto result = channel_timestamp_loggers_.try_emplace(
2122 std::make_pair(channel, connection),
2123 std::make_shared<RemoteMessageSender>(
2124 event_loop()->MakeSender<RemoteMessage>(
2125 timestamp_channel->name()->string_view()),
2126 event_loop()));
2127
2128 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2129 .second);
2130 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002131}
2132
Austin Schuhdda74ec2021-01-03 19:30:37 -08002133TimestampedMessage LogReader::State::PopOldest() {
James Kuszmaula16a7912022-06-17 10:58:12 -07002134 if (message_queuer_.has_value()) {
2135 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2136 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2137 message_queuer_->SetState(
2138 message.value().monotonic_event_time +
2139 std::chrono::duration_cast<std::chrono::nanoseconds>(
2140 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2141 return message.value();
2142 } else {
2143 CHECK(timestamp_mapper_ != nullptr);
2144 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2145 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002146
James Kuszmaula16a7912022-06-17 10:58:12 -07002147 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002148
James Kuszmaula16a7912022-06-17 10:58:12 -07002149 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2150 << result.monotonic_event_time;
2151 timestamp_mapper_->PopFront();
2152 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002153
James Kuszmaula16a7912022-06-17 10:58:12 -07002154 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002155
James Kuszmaula16a7912022-06-17 10:58:12 -07002156 VLOG(1) << "Popped " << result
2157 << configuration::CleanedChannelToString(
2158 event_loop_->configuration()->channels()->Get(
2159 factory_channel_index_[result.channel_index]));
2160 return result;
2161 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002162}
2163
James Kuszmaula16a7912022-06-17 10:58:12 -07002164BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2165 if (!message_queuer_.has_value()) {
2166 return SingleThreadedOldestMessageTime();
2167 }
2168 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2169 if (!message.has_value()) {
2170 return BootTimestamp::max_time();
2171 }
2172 if (message.value().monotonic_event_time.boot == boot_count()) {
2173 ObserveNextMessage(message.value().monotonic_event_time.time,
2174 message.value().realtime_event_time);
2175 }
2176 return message.value().monotonic_event_time;
2177}
2178
2179BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2180 CHECK(!message_queuer_.has_value())
2181 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2182 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002183 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002184 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002185 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002186 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2187 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002188 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002189 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002190 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002191 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002192 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2193 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2194 result_ptr->realtime_event_time);
2195 }
Austin Schuh58646e22021-08-23 23:51:46 -07002196 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002197}
2198
2199void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002200 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002201
Austin Schuhe639ea12021-01-25 13:00:22 -08002202 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2203 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002204}
2205
2206void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002207 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002208 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002209 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002210 for (size_t i = 0; i < channels_.size(); ++i) {
2211 channels_[i].reset();
2212 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002213 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002214 channel_timestamp_loggers_.clear();
2215 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002216 event_loop_unique_ptr_.reset();
2217 event_loop_ = nullptr;
2218 timer_handler_ = nullptr;
2219 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002220 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002221}
2222
Austin Schuhe33c08d2022-02-03 18:15:21 -08002223void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2224 if (start_time != realtime_clock::min_time) {
2225 start_event_notifier_ = std::make_unique<EventNotifier>(
2226 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2227 }
2228}
2229
2230void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2231 if (end_time != realtime_clock::max_time) {
2232 end_event_notifier_ = std::make_unique<EventNotifier>(
2233 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2234 }
2235}
2236
2237void LogReader::State::ObserveNextMessage(
2238 monotonic_clock::time_point monotonic_event,
2239 realtime_clock::time_point realtime_event) {
2240 if (start_event_notifier_) {
2241 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2242 }
2243 if (end_event_notifier_) {
2244 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2245 }
2246}
2247
2248void LogReader::State::ClearTimeFlags() {
2249 start_event_notifier_.reset();
2250 end_event_notifier_.reset();
2251}
2252
2253void LogReader::State::NotifyLogfileStart() {
2254 if (start_event_notifier_) {
2255 if (start_event_notifier_->realtime_event_time() >
2256 realtime_start_time(boot_count())) {
2257 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2258 << " > " << realtime_start_time(boot_count());
2259 return;
2260 }
2261 }
2262 if (found_last_message_) {
2263 VLOG(1) << "Last message already found, bailing";
2264 return;
2265 }
2266 RunOnStart();
2267}
2268
2269void LogReader::State::NotifyFlagStart() {
2270 if (start_event_notifier_->realtime_event_time() >=
2271 realtime_start_time(boot_count())) {
2272 RunOnStart();
2273 }
2274}
2275
2276void LogReader::State::NotifyLogfileEnd() {
2277 if (found_last_message_) {
2278 return;
2279 }
2280
2281 if (!stopped_ && started_) {
2282 RunOnEnd();
2283 }
2284}
2285
2286void LogReader::State::NotifyFlagEnd() {
2287 if (!stopped_ && started_) {
2288 RunOnEnd();
2289 SetFoundLastMessage(true);
2290 }
2291}
2292
James Kuszmaulc3f34d12022-08-15 15:57:55 -07002293void LogReader::State::MaybeSetClockOffset() {
James Kuszmaul09632422022-05-25 15:56:19 -07002294 if (node_event_loop_factory_ == nullptr) {
2295 // If not running with simulated event loop, set the monotonic clock
2296 // offset.
2297 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2298
2299 if (start_event_notifier_) {
2300 start_event_notifier_->SetClockOffset(clock_offset_);
2301 }
2302 if (end_event_notifier_) {
2303 end_event_notifier_->SetClockOffset(clock_offset_);
2304 }
2305 }
2306}
2307
James Kuszmaulb67409b2022-06-20 16:25:03 -07002308void LogReader::SetRealtimeReplayRate(double replay_rate) {
2309 CHECK(event_loop_factory_ != nullptr)
2310 << ": Can't set replay rate without an event loop factory (have you "
2311 "called Register()?).";
2312 event_loop_factory_->SetRealtimeReplayRate(replay_rate);
2313}
2314
Austin Schuhe309d2a2019-11-29 13:25:21 -08002315} // namespace logger
2316} // namespace aos