blob: bdee44f4f4e9b0d778b1125ecf762148cc2cec5d [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08007
Tyler Chatowbf0609c2021-07-31 16:13:27 -07008#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -08009#include <vector>
10
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070014#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070015#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080016#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
James Kuszmaul09632422022-05-25 15:56:19 -070018#include "aos/json_to_flatbuffer.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080019#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080020#include "aos/network/remote_message_generated.h"
21#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080022#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080023#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070025#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070026#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080028#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080029
Austin Schuh15649d62019-12-28 16:36:38 -080030DEFINE_bool(skip_missing_forwarding_entries, false,
31 "If true, drop any forwarding entries with missing data. If "
32 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080033
Austin Schuh0ca1fd32020-12-18 22:53:05 -080034DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080035
Austin Schuh2f8fd752020-09-01 22:38:28 -070036DEFINE_bool(skip_order_validation, false,
37 "If true, ignore any out of orderness in replay");
38
Austin Schuhf0688662020-12-19 15:37:45 -080039DEFINE_double(
40 time_estimation_buffer_seconds, 2.0,
41 "The time to buffer ahead in the log file to accurately reconstruct time.");
42
Austin Schuhe33c08d2022-02-03 18:15:21 -080043DEFINE_string(
44 start_time, "",
45 "If set, start at this point in time in the log on the realtime clock.");
46DEFINE_string(
47 end_time, "",
48 "If set, end at this point in time in the log on the realtime clock.");
49
James Kuszmaul09632422022-05-25 15:56:19 -070050DEFINE_bool(drop_realtime_messages_before_start, false,
51 "If set, will drop any messages sent before the start of the "
52 "logfile in realtime replay. Setting this guarantees consistency "
53 "in timing with the original logfile, but means that you lose "
54 "access to fetched low-frequency messages.");
55
James Kuszmaula16a7912022-06-17 10:58:12 -070056DEFINE_double(
57 threaded_look_ahead_seconds, 2.0,
58 "Time, in seconds, to add to look-ahead when using multi-threaded replay. "
59 "Can validly be zero, but higher values are encouraged for realtime replay "
60 "in order to prevent the replay from ever having to block on waiting for "
61 "the reader to find the next message.");
62
Austin Schuhe309d2a2019-11-29 13:25:21 -080063namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070064namespace configuration {
65// We don't really want to expose this publicly, but log reader doesn't really
66// want to re-implement it.
67void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
68 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070069} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080070namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070071namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080072
Austin Schuh1c227352021-09-17 12:53:54 -070073bool CompareChannels(const Channel *c,
74 ::std::pair<std::string_view, std::string_view> p) {
75 int name_compare = c->name()->string_view().compare(p.first);
76 if (name_compare == 0) {
77 return c->type()->string_view() < p.second;
78 } else if (name_compare < 0) {
79 return true;
80 } else {
81 return false;
82 }
83}
84
85bool EqualsChannels(const Channel *c,
86 ::std::pair<std::string_view, std::string_view> p) {
87 return c->name()->string_view() == p.first &&
88 c->type()->string_view() == p.second;
89}
90
Austin Schuh0de30f32020-12-06 12:44:28 -080091// Copies the channel, removing the schema as we go. If new_name is provided,
92// it is used instead of the name inside the channel. If new_type is provided,
93// it is used instead of the type in the channel.
94flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
95 std::string_view new_name,
96 std::string_view new_type,
97 flatbuffers::FlatBufferBuilder *fbb) {
98 flatbuffers::Offset<flatbuffers::String> name_offset =
99 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
100 : new_name);
101 flatbuffers::Offset<flatbuffers::String> type_offset =
102 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
103 flatbuffers::Offset<flatbuffers::String> source_node_offset =
104 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
105 : 0;
106
107 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
108 destination_nodes_offset =
109 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
110
111 flatbuffers::Offset<
112 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
113 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
114
115 Channel::Builder channel_builder(*fbb);
116 channel_builder.add_name(name_offset);
117 channel_builder.add_type(type_offset);
118 if (c->has_frequency()) {
119 channel_builder.add_frequency(c->frequency());
120 }
121 if (c->has_max_size()) {
122 channel_builder.add_max_size(c->max_size());
123 }
124 if (c->has_num_senders()) {
125 channel_builder.add_num_senders(c->num_senders());
126 }
127 if (c->has_num_watchers()) {
128 channel_builder.add_num_watchers(c->num_watchers());
129 }
130 if (!source_node_offset.IsNull()) {
131 channel_builder.add_source_node(source_node_offset);
132 }
133 if (!destination_nodes_offset.IsNull()) {
134 channel_builder.add_destination_nodes(destination_nodes_offset);
135 }
136 if (c->has_logger()) {
137 channel_builder.add_logger(c->logger());
138 }
139 if (!logger_nodes_offset.IsNull()) {
140 channel_builder.add_logger_nodes(logger_nodes_offset);
141 }
142 if (c->has_read_method()) {
143 channel_builder.add_read_method(c->read_method());
144 }
145 if (c->has_num_readers()) {
146 channel_builder.add_num_readers(c->num_readers());
147 }
148 return channel_builder.Finish();
149}
150
Austin Schuhe309d2a2019-11-29 13:25:21 -0800151namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800152using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700153} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800154
Austin Schuhe33c08d2022-02-03 18:15:21 -0800155// Class to manage triggering events on the RT clock while replaying logs. Since
156// the RT clock can only change when we get a message, we only need to update
157// our timers when new messages are read.
158class EventNotifier {
159 public:
160 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
161 std::string_view name,
162 realtime_clock::time_point realtime_event_time)
163 : event_loop_(event_loop),
164 fn_(std::move(fn)),
165 realtime_event_time_(realtime_event_time) {
166 CHECK(event_loop_);
167 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
168
169 if (event_loop_->node() != nullptr) {
170 event_timer_->set_name(
171 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
172 } else {
173 event_timer_->set_name(name);
174 }
175 }
176
177 ~EventNotifier() { event_timer_->Disable(); }
178
James Kuszmaul09632422022-05-25 15:56:19 -0700179 // Sets the clock offset for realtime playback.
180 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
181 clock_offset_ = clock_offset;
182 }
183
Austin Schuhe33c08d2022-02-03 18:15:21 -0800184 // Returns the event trigger time.
185 realtime_clock::time_point realtime_event_time() const {
186 return realtime_event_time_;
187 }
188
189 // Observes the next message and potentially calls the callback or updates the
190 // timer.
191 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
192 realtime_clock::time_point realtime_message_time) {
193 if (realtime_message_time < realtime_event_time_) {
194 return;
195 }
196 if (called_) {
197 return;
198 }
199
200 // Move the callback wakeup time to the correct time (or make it now if
201 // there's a gap in time) now that we know it is before the next
202 // message.
203 const monotonic_clock::time_point candidate_monotonic =
204 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
205 const monotonic_clock::time_point monotonic_now =
206 event_loop_->monotonic_now();
207 if (candidate_monotonic < monotonic_now) {
208 // Whops, time went backwards. Just do it now.
209 HandleTime();
210 } else {
James Kuszmaul09632422022-05-25 15:56:19 -0700211 event_timer_->Setup(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800212 }
213 }
214
215 private:
216 void HandleTime() {
217 if (!called_) {
218 called_ = true;
219 fn_();
220 }
221 }
222
223 EventLoop *event_loop_ = nullptr;
224 TimerHandler *event_timer_ = nullptr;
225 std::function<void()> fn_;
226
227 const realtime_clock::time_point realtime_event_time_ =
228 realtime_clock::min_time;
229
James Kuszmaul09632422022-05-25 15:56:19 -0700230 std::chrono::nanoseconds clock_offset_{0};
231
Austin Schuhe33c08d2022-02-03 18:15:21 -0800232 bool called_ = false;
233};
234
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800235LogReader::LogReader(std::string_view filename,
236 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800237 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800238
Austin Schuh287d43d2020-12-04 20:19:33 -0800239LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800240 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800241 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800242 replay_configuration_(replay_configuration) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800243 SetStartTime(FLAGS_start_time);
244 SetEndTime(FLAGS_end_time);
245
Austin Schuh0ca51f32020-12-25 21:51:45 -0800246 CHECK_GT(log_files_.size(), 0u);
247 {
248 // Validate that we have the same config everwhere. This will be true if
249 // all the parts were sorted together and the configs match.
250 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800251 for (const LogFile &log_file : log_files_) {
252 if (log_file.config.get() == nullptr) {
253 LOG(FATAL) << "Couldn't find a config in " << log_file;
254 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800255 if (config == nullptr) {
256 config = log_file.config.get();
257 } else {
258 CHECK_EQ(config, log_file.config.get());
259 }
260 }
261 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800262
Austin Schuh6331ef92020-01-07 18:28:09 -0800263 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800264
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700265 // Remap all existing remote timestamp channels. They will be recreated, and
266 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700267 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800268 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
269 "log_reader", node);
270
271 absl::btree_set<std::string_view> remote_nodes;
272
273 for (const Channel *channel : *logged_configuration()->channels()) {
274 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
275 continue;
276 }
277 if (!channel->has_destination_nodes()) {
278 continue;
279 }
280 for (const Connection *connection : *channel->destination_nodes()) {
281 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
282 node)) {
283 // Start by seeing if the split timestamp channels are being used for
284 // this message. If so, remap them.
285 const Channel *timestamp_channel = configuration::GetChannel(
286 logged_configuration(),
287 finder.SplitChannelName(channel, connection),
288 RemoteMessage::GetFullyQualifiedName(), "", node, true);
289
290 if (timestamp_channel != nullptr) {
291 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
292 RemapLoggedChannel<RemoteMessage>(
293 timestamp_channel->name()->string_view(), node);
294 }
295 continue;
296 }
297
298 // Otherwise collect this one up as a node to look for a combined
299 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700300 LOG(WARNING) << "Failed to find channel "
301 << finder.SplitChannelName(channel, connection)
302 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800303 remote_nodes.insert(connection->name()->string_view());
304 }
305 }
306 }
307
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700308 std::vector<const Node *> timestamp_logger_nodes =
309 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800310 for (const std::string_view remote_node : remote_nodes) {
311 const std::string channel = finder.CombinedChannelName(remote_node);
312
Austin Schuh0de30f32020-12-06 12:44:28 -0800313 // See if the log file is an old log with MessageHeader channels in it, or
314 // a newer log with RemoteMessage. If we find an older log, rename the
315 // type too along with the name.
316 if (HasChannel<MessageHeader>(channel, node)) {
317 CHECK(!HasChannel<RemoteMessage>(channel, node))
318 << ": Can't have both a MessageHeader and RemoteMessage remote "
319 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800320 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
321 // careful about updating the config, but there are fewer and fewer logs
322 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800323 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
324 "aos.message_bridge.RemoteMessage");
325 } else {
326 CHECK(HasChannel<RemoteMessage>(channel, node))
327 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
328 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
329 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800330 // Only bother to remap if there's something on the channel. We can
331 // tell if the channel was marked NOT_LOGGED or not. This makes the
332 // config not change un-necesarily when we replay a log with NOT_LOGGED
333 // messages.
334 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
335 RemapLoggedChannel<RemoteMessage>(channel, node);
336 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800337 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700338 }
339 }
340
Austin Schuh6aa77be2020-02-22 21:06:40 -0800341 if (replay_configuration) {
342 CHECK_EQ(configuration::MultiNode(configuration()),
343 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700344 << ": Log file and replay config need to both be multi or single "
345 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800346 }
347
Austin Schuh6f3babe2020-01-26 20:34:50 -0800348 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700349 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800350 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800351 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700352 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800353 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700354 << ": Log file and replay config need to have matching nodes "
355 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700356 for (const Node *node : *logged_configuration()->nodes()) {
357 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
359 << " in logged config that is not present in the replay "
360 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700361 }
362 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800363 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800364 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800365 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800366}
367
Austin Schuh6aa77be2020-02-22 21:06:40 -0800368LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700369 if (event_loop_factory_unique_ptr_) {
370 Deregister();
371 } else if (event_loop_factory_ != nullptr) {
372 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
373 "is destroyed";
374 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700375 // Zero out some buffers. It's easy to do use-after-frees on these, so make
376 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700377 if (remapped_configuration_buffer_) {
378 remapped_configuration_buffer_->Wipe();
379 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800380}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800381
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800382const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800383 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800384}
385
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800386const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800387 return remapped_configuration_;
388}
389
Austin Schuh07676622021-01-21 18:59:17 -0800390std::vector<const Node *> LogReader::LoggedNodes() const {
391 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800392}
Austin Schuh15649d62019-12-28 16:36:38 -0800393
Austin Schuh11d43732020-09-21 17:28:30 -0700394monotonic_clock::time_point LogReader::monotonic_start_time(
395 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800396 State *state =
397 states_[configuration::GetNodeIndex(configuration(), node)].get();
398 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
399
Austin Schuhf665eb42022-02-03 18:26:25 -0800400 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800401}
402
Austin Schuh11d43732020-09-21 17:28:30 -0700403realtime_clock::time_point LogReader::realtime_start_time(
404 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800405 State *state =
406 states_[configuration::GetNodeIndex(configuration(), node)].get();
407 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
408
Austin Schuhf665eb42022-02-03 18:26:25 -0800409 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800410}
411
Austin Schuh58646e22021-08-23 23:51:46 -0700412void LogReader::OnStart(std::function<void()> fn) {
413 CHECK(!configuration::MultiNode(configuration()));
414 OnStart(nullptr, std::move(fn));
415}
416
417void LogReader::OnStart(const Node *node, std::function<void()> fn) {
418 const int node_index = configuration::GetNodeIndex(configuration(), node);
419 CHECK_GE(node_index, 0);
420 CHECK_LT(node_index, static_cast<int>(states_.size()));
421 State *state = states_[node_index].get();
422 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
423
424 state->OnStart(std::move(fn));
425}
426
James Kuszmaula16a7912022-06-17 10:58:12 -0700427void LogReader::State::QueueThreadUntil(BootTimestamp time) {
428 if (threading_ == ThreadedBuffering::kYes) {
429 CHECK(!message_queuer_.has_value()) << "Can't start thread twice.";
430 message_queuer_.emplace(
431 [this](const BootTimestamp queue_until) {
432 // This will be called whenever anything prompts us for any state
433 // change; there may be wakeups that result in us not having any new
434 // data to push (even if we aren't done), in which case we will return
435 // nullopt but not done().
436 if (last_queued_message_.has_value() &&
437 queue_until < last_queued_message_) {
438 return util::ThreadedQueue<TimestampedMessage,
439 BootTimestamp>::PushResult{
440 std::nullopt, false,
441 last_queued_message_ == BootTimestamp::max_time()};
442 }
443 TimestampedMessage *message = timestamp_mapper_->Front();
444 // Upon reaching the end of the log, exit.
445 if (message == nullptr) {
446 last_queued_message_ = BootTimestamp::max_time();
447 return util::ThreadedQueue<TimestampedMessage,
448 BootTimestamp>::PushResult{std::nullopt,
449 false, true};
450 }
451 last_queued_message_ = message->monotonic_event_time;
452 const util::ThreadedQueue<TimestampedMessage,
453 BootTimestamp>::PushResult result{
454 *message, queue_until >= last_queued_message_, false};
455 timestamp_mapper_->PopFront();
456 SeedSortedMessages();
457 return result;
458 },
459 time);
460 // Spin until the first few seconds of messages are queued up so that we
461 // don't end up with delays/inconsistent timing during the first few seconds
462 // of replay.
463 message_queuer_->WaitForNoMoreWork();
464 }
465}
466
Austin Schuh58646e22021-08-23 23:51:46 -0700467void LogReader::State::OnStart(std::function<void()> fn) {
468 on_starts_.emplace_back(std::move(fn));
469}
470
471void LogReader::State::RunOnStart() {
472 SetRealtimeOffset(monotonic_start_time(boot_count()),
473 realtime_start_time(boot_count()));
474
475 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
476 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800477 auto fn = [this]() {
478 for (size_t i = 0; i < on_starts_.size(); ++i) {
479 on_starts_[i]();
480 }
481 };
482 if (event_loop_factory_) {
483 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
484 } else {
485 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700486 }
487 stopped_ = false;
488 started_ = true;
489}
490
491void LogReader::OnEnd(std::function<void()> fn) {
492 CHECK(!configuration::MultiNode(configuration()));
493 OnEnd(nullptr, std::move(fn));
494}
495
496void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
497 const int node_index = configuration::GetNodeIndex(configuration(), node);
498 CHECK_GE(node_index, 0);
499 CHECK_LT(node_index, static_cast<int>(states_.size()));
500 State *state = states_[node_index].get();
501 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
502
503 state->OnEnd(std::move(fn));
504}
505
506void LogReader::State::OnEnd(std::function<void()> fn) {
507 on_ends_.emplace_back(std::move(fn));
508}
509
510void LogReader::State::RunOnEnd() {
511 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
512 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800513 auto fn = [this]() {
514 for (size_t i = 0; i < on_ends_.size(); ++i) {
515 on_ends_[i]();
516 }
517 };
518 if (event_loop_factory_) {
519 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
520 } else {
521 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700522 }
523
524 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800525 started_ = true;
James Kuszmaula16a7912022-06-17 10:58:12 -0700526 if (message_queuer_.has_value()) {
527 message_queuer_->StopPushing();
528 }
Austin Schuh58646e22021-08-23 23:51:46 -0700529}
530
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800531void LogReader::Register() {
532 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800533 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800534 Register(event_loop_factory_unique_ptr_.get());
535}
536
Austin Schuh58646e22021-08-23 23:51:46 -0700537void LogReader::RegisterWithoutStarting(
538 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800539 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700540 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800541 filters_ =
542 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800543 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700544 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800545 chrono::duration_cast<chrono::nanoseconds>(
546 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800547
Austin Schuhe639ea12021-01-25 13:00:22 -0800548 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700549 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800550 const size_t node_index =
551 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800552 std::vector<LogParts> filtered_parts = FilterPartsForNode(
553 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800554
James Kuszmaula16a7912022-06-17 10:58:12 -0700555 // We don't run with threading on the buffering for simulated event loops
556 // because we haven't attempted to validate how the interactions beteen the
557 // buffering and the timestamp mapper works when running multiple nodes
558 // concurrently.
Austin Schuh287d43d2020-12-04 20:19:33 -0800559 states_[node_index] = std::make_unique<State>(
560 filtered_parts.size() == 0u
561 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700562 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700563 filters_.get(), node, State::ThreadedBuffering::kNo);
Austin Schuh8bd96322020-02-13 21:18:22 -0800564 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700565 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800566 event_loop_factory_->GetNodeEventLoopFactory(node),
567 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700568
569 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800570 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800571 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800572 filters_->SetTimestampMappers(std::move(timestamp_mappers));
573
574 // Note: this needs to be set before any times are pulled, or we won't observe
575 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800576 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700577
Austin Schuh287d43d2020-12-04 20:19:33 -0800578 for (const Node *node : configuration::GetNodes(configuration())) {
579 const size_t node_index =
580 configuration::GetNodeIndex(configuration(), node);
581 State *state = states_[node_index].get();
582 for (const Node *other_node : configuration::GetNodes(configuration())) {
583 const size_t other_node_index =
584 configuration::GetNodeIndex(configuration(), other_node);
585 State *other_state = states_[other_node_index].get();
586 if (other_state != state) {
587 state->AddPeer(other_state);
588 }
589 }
590 }
591
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700592 // Register after making all the State objects so we can build references
593 // between them.
594 for (const Node *node : configuration::GetNodes(configuration())) {
595 const size_t node_index =
596 configuration::GetNodeIndex(configuration(), node);
597 State *state = states_[node_index].get();
598
Austin Schuh58646e22021-08-23 23:51:46 -0700599 // If we didn't find any log files with data in them, we won't ever get a
600 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700601 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700602 continue;
603 }
604 ++live_nodes_;
605
606 NodeEventLoopFactory *node_factory =
607 event_loop_factory_->GetNodeEventLoopFactory(node);
608 node_factory->OnStartup([this, state, node]() {
609 RegisterDuringStartup(state->MakeEventLoop(), node);
610 });
611 node_factory->OnShutdown([this, state, node]() {
612 RegisterDuringStartup(nullptr, node);
613 state->DestroyEventLoop();
614 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700615 }
616
James Kuszmaul46d82582020-05-09 19:50:09 -0700617 if (live_nodes_ == 0) {
618 LOG(FATAL)
619 << "Don't have logs from any of the nodes in the replay config--are "
620 "you sure that the replay config matches the original config?";
621 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800622
Austin Schuh87dd3832021-01-01 23:07:31 -0800623 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800624
Austin Schuh858c9f32020-08-31 16:56:12 -0700625 for (std::unique_ptr<State> &state : states_) {
626 state->SeedSortedMessages();
627 }
628
Austin Schuh6f3babe2020-01-26 20:34:50 -0800629 // Forwarding is tracked per channel. If it is enabled, we want to turn it
630 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700631 // nodes, and also replayed on the other nodes. This may not satisfy all
632 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800633 if (configuration::MultiNode(event_loop_factory_->configuration())) {
634 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
635 const Channel *channel = logged_configuration()->channels()->Get(i);
636 const Node *node = configuration::GetNode(
637 configuration(), channel->source_node()->string_view());
638
Austin Schuh8bd96322020-02-13 21:18:22 -0800639 State *state =
640 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800641
642 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700643 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800644
645 event_loop_factory_->DisableForwarding(remapped_channel);
646 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700647
648 // If we are replaying a log, we don't want a bunch of redundant messages
649 // from both the real message bridge and simulated message bridge.
650 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800651 }
Austin Schuh891214d2021-11-11 20:35:02 -0800652
653 // Write pseudo start times out to file now that we are all setup.
654 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700655}
656
657void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
658 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800659 StartAfterRegister(event_loop_factory);
660}
661
662void LogReader::StartAfterRegister(
663 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700664 // We want to start the log file at the last start time of the log files
665 // from all the nodes. Compute how long each node's simulation needs to run
666 // to move time to this point.
667 distributed_clock::time_point start_time = distributed_clock::min_time;
668
669 // TODO(austin): We want an "OnStart" callback for each node rather than
670 // running until the last node.
671
672 for (std::unique_ptr<State> &state : states_) {
673 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
674 << " for node " << MaybeNodeName(state->node()) << "now "
675 << state->monotonic_now();
676 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
677 continue;
678 }
679 // And start computing the start time on the distributed clock now that
680 // that works.
681 start_time = std::max(
682 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
683 }
684
685 // TODO(austin): If a node doesn't have a start time, we might not queue
686 // enough. If this happens, we'll explode with a frozen error eventually.
687
688 CHECK_GE(start_time, distributed_clock::epoch())
689 << ": Hmm, we have a node starting before the start of time. Offset "
690 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800691
Austin Schuhcde938c2020-02-02 17:30:07 -0800692 // While we are starting the system up, we might be relying on matching data
693 // to timestamps on log files where the timestamp log file starts before the
694 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800695 {
696 const bool prior_ignore_missing_data = ignore_missing_data_;
697 ignore_missing_data_ = true;
698 VLOG(1) << "Running until " << start_time << " in Register";
699 event_loop_factory_->RunFor(start_time.time_since_epoch());
700 VLOG(1) << "At start time";
701 // Now that we are running for real, missing data means that the log file is
702 // corrupted or went wrong.
703 ignore_missing_data_ = prior_ignore_missing_data;
704 }
Austin Schuh92547522019-12-28 14:33:43 -0800705
Austin Schuh8bd96322020-02-13 21:18:22 -0800706 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700707 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700708 if (state->realtime_start_time(0) != realtime_clock::min_time) {
709 state->SetRealtimeOffset(state->monotonic_start_time(0),
710 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700711 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700712 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
713 << " for node " << MaybeNodeName(state->event_loop()->node())
714 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700715 }
716
717 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800718 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800719 }
720}
721
Austin Schuh2f8fd752020-09-01 22:38:28 -0700722message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800723 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800724 if (filters_) {
725 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800726 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800727 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800728}
729
James Kuszmaul09632422022-05-25 15:56:19 -0700730// TODO(jkuszmaul): Make in-line modifications to
731// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
732// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800733void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700734 filters_ =
735 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
736 event_loop->configuration(), logged_configuration(),
737 log_files_[0].boots, FLAGS_skip_order_validation,
738 chrono::duration_cast<chrono::nanoseconds>(
739 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
740
741 std::vector<TimestampMapper *> timestamp_mappers;
742 for (const Node *node : configuration::GetNodes(configuration())) {
743 const size_t node_index =
744 configuration::GetNodeIndex(configuration(), node);
745 std::vector<LogParts> filtered_parts = FilterPartsForNode(
746 log_files_, node != nullptr ? node->name()->string_view() : "");
747
748 states_[node_index] = std::make_unique<State>(
749 filtered_parts.size() == 0u
750 ? nullptr
751 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaula16a7912022-06-17 10:58:12 -0700752 filters_.get(), node, State::ThreadedBuffering::kYes);
James Kuszmaul09632422022-05-25 15:56:19 -0700753 State *state = states_[node_index].get();
754
755 state->SetChannelCount(logged_configuration()->channels()->size());
756 timestamp_mappers.emplace_back(state->timestamp_mapper());
757 }
758
759 filters_->SetTimestampMappers(std::move(timestamp_mappers));
760
761 for (const Node *node : configuration::GetNodes(configuration())) {
762 const size_t node_index =
763 configuration::GetNodeIndex(configuration(), node);
764 State *state = states_[node_index].get();
765 for (const Node *other_node : configuration::GetNodes(configuration())) {
766 const size_t other_node_index =
767 configuration::GetNodeIndex(configuration(), other_node);
768 State *other_state = states_[other_node_index].get();
769 if (other_state != state) {
770 state->AddPeer(other_state);
771 }
772 }
773 }
774 for (const Node *node : configuration::GetNodes(configuration())) {
775 if (node == nullptr || node->name()->string_view() ==
776 event_loop->node()->name()->string_view()) {
777 Register(event_loop, event_loop->node());
778 } else {
779 Register(nullptr, node);
780 }
781 }
Austin Schuh58646e22021-08-23 23:51:46 -0700782}
783
784void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800785 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700786 states_[configuration::GetNodeIndex(configuration(), node)].get();
787
788 // If we didn't find any log files with data in them, we won't ever get a
789 // callback or be live. So skip the rest of the setup.
James Kuszmaula16a7912022-06-17 10:58:12 -0700790 if (state->SingleThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -0700791 return;
792 }
James Kuszmaul09632422022-05-25 15:56:19 -0700793
794 if (event_loop != nullptr) {
795 ++live_nodes_;
796 }
Austin Schuh58646e22021-08-23 23:51:46 -0700797
798 if (event_loop_factory_ != nullptr) {
799 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
800 [this, event_loop, node]() {
801 RegisterDuringStartup(event_loop, node);
802 });
803 } else {
804 RegisterDuringStartup(event_loop, node);
805 }
806}
807
808void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700809 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700810 CHECK(event_loop->configuration() == configuration());
811 }
812
813 State *state =
814 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800815
James Kuszmaul09632422022-05-25 15:56:19 -0700816 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800817 state->ClearTimeFlags();
818 }
819
Austin Schuh858c9f32020-08-31 16:56:12 -0700820 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800821
Tyler Chatow67ddb032020-01-12 14:30:04 -0800822 // We don't run timing reports when trying to print out logged data, because
823 // otherwise we would end up printing out the timing reports themselves...
824 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700825 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700826 event_loop->SkipTimingReport();
827 event_loop->SkipAosLog();
828 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800829
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700830 for (size_t logged_channel_index = 0;
831 logged_channel_index < logged_configuration()->channels()->size();
832 ++logged_channel_index) {
833 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700834 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700835 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800836
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700837 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700838 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700839
840 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700841
Austin Schuh58646e22021-08-23 23:51:46 -0700842 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
843 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700844 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700845 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800846
Austin Schuh58646e22021-08-23 23:51:46 -0700847 // We've got a message which is being forwarded to this node.
848 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700849
850 source_state =
851 states_[configuration::GetNodeIndex(configuration(), source_node)]
852 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800853 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700854
Austin Schuh58646e22021-08-23 23:51:46 -0700855 // We are the source, and it is forwarded.
856 const bool is_forwarded =
857 configuration::ChannelIsSendableOnNode(channel, node) &&
858 configuration::ConnectionCount(channel);
859
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700860 state->SetChannel(
861 logged_channel_index,
862 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700863 event_loop && logged &&
864 configuration::ChannelIsReadableOnNode(channel, node)
865 ? event_loop->MakeRawSender(channel)
866 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700867 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700868
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700869 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700870 const Node *source_node = configuration::GetNode(
871 configuration(), channel->source_node()->string_view());
872
873 for (const Connection *connection : *channel->destination_nodes()) {
874 const bool delivery_time_is_logged =
875 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
876 source_node);
877
878 if (delivery_time_is_logged) {
879 State *destination_state =
880 states_[configuration::GetNodeIndex(
881 configuration(), connection->name()->string_view())]
882 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700883 if (destination_state) {
884 destination_state->SetRemoteTimestampSender(
885 logged_channel_index,
886 event_loop ? state->RemoteTimestampSender(channel, connection)
887 : nullptr);
888 }
Austin Schuh58646e22021-08-23 23:51:46 -0700889 }
890 }
891 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800892 }
893
Austin Schuh58646e22021-08-23 23:51:46 -0700894 if (!event_loop) {
895 state->ClearRemoteTimestampSenders();
896 state->set_timer_handler(nullptr);
897 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800898 return;
899 }
900
Austin Schuh858c9f32020-08-31 16:56:12 -0700901 state->set_timer_handler(event_loop->AddTimer([this, state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -0700902 if (state->MultiThreadedOldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800903 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700904 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaula16a7912022-06-17 10:58:12 -0700905 if (exit_on_finish_ && live_nodes_ == 0 &&
906 event_loop_factory_ != nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -0700907 CHECK_NOTNULL(event_loop_factory_)->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800908 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800909 return;
910 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700911
Austin Schuhdda74ec2021-01-03 19:30:37 -0800912 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700913
914 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
915 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800916
Austin Schuhe309d2a2019-11-29 13:25:21 -0800917 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700918 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700919 if (event_loop_factory_ != nullptr) {
920 // Only enforce exact timing in simulation.
921 if (!FLAGS_skip_order_validation) {
922 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
923 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
924 << monotonic_now << " trying to send "
925 << timestamped_message.monotonic_event_time << " failure "
926 << state->DebugString();
927 } else if (BootTimestamp{.boot = state->boot_count(),
928 .time = monotonic_now} !=
929 timestamped_message.monotonic_event_time) {
930 LOG(WARNING) << "Check failed: monotonic_now == "
931 "timestamped_message.monotonic_event_time) ("
932 << monotonic_now << " vs. "
933 << timestamped_message.monotonic_event_time
934 << "): " << FlatbufferToJson(state->event_loop()->node())
935 << " Now " << monotonic_now << " trying to send "
936 << timestamped_message.monotonic_event_time << " failure "
937 << state->DebugString();
938 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700939 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800940
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700941 if (timestamped_message.monotonic_event_time.time >
942 state->monotonic_start_time(
943 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700944 event_loop_factory_ != nullptr ||
945 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800946 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800947 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -0700948 BootTimestamp::min_time() &&
949 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800950 // Confirm that the message was sent on the sending node before the
951 // destination node (this node). As a proxy, do this by making sure
952 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800953 //
954 // TODO(austin): <= means that the cause message (which we know) could
955 // happen after the effect even though we know they are at the same
956 // time. I doubt anyone will notice for a bit, but we should really
957 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -0700958 BootTimestamp monotonic_remote_now =
959 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700960 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -0700961 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -0800962 monotonic_remote_now.boot)
963 << state->event_loop()->node()->name()->string_view() << " to "
964 << state->remote_node(timestamped_message.channel_index)
965 ->name()
966 ->string_view()
967 << " while trying to send a message on "
968 << configuration::CleanedChannelToString(
969 logged_configuration()->channels()->Get(
970 timestamped_message.channel_index))
971 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700972 CHECK_LE(timestamped_message.monotonic_remote_time,
973 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700974 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800975 << state->remote_node(timestamped_message.channel_index)
976 ->name()
977 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800978 << " while trying to send a message on "
979 << configuration::CleanedChannelToString(
980 logged_configuration()->channels()->Get(
981 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700982 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700983 } else if (monotonic_remote_now.boot !=
984 timestamped_message.monotonic_remote_time.boot) {
985 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
986 << " vs "
987 << timestamped_message.monotonic_remote_time.boot;
988 } else if (timestamped_message.monotonic_remote_time >
989 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700990 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800991 << "Check failed: timestamped_message.monotonic_remote_time < "
992 "state->monotonic_remote_now(timestamped_message.channel_"
993 "index) ("
994 << timestamped_message.monotonic_remote_time << " vs. "
995 << state->monotonic_remote_now(
996 timestamped_message.channel_index)
997 << ") " << state->event_loop()->node()->name()->string_view()
998 << " to "
999 << state->remote_node(timestamped_message.channel_index)
1000 ->name()
1001 ->string_view()
1002 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001003 << " ("
1004 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001005 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001006 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001007 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001008 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001009 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001010 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 << ") " << state->DebugString();
1012 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001013 }
1014
Austin Schuh15649d62019-12-28 16:36:38 -08001015 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001016 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001017 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001018
Austin Schuh2f8fd752020-09-01 22:38:28 -07001019 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -07001020 << timestamped_message.monotonic_event_time << " "
1021 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001022 // TODO(austin): std::move channel_data in and make that efficient in
1023 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001024 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001025 } else if (state->found_last_message() ||
1026 (!ignore_missing_data_ &&
1027 // When starting up, we can have data which was sent before
1028 // the log starts, but the timestamp was after the log
1029 // starts. This is unreasonable to avoid, so ignore the
1030 // missing data.
1031 timestamped_message.monotonic_remote_time.time >=
1032 state->monotonic_remote_start_time(
1033 timestamped_message.monotonic_remote_time.boot,
1034 timestamped_message.channel_index) &&
1035 !FLAGS_skip_missing_forwarding_entries)) {
1036 if (!state->found_last_message()) {
1037 // We've found a timestamp without data that we expect to have data
1038 // for. This likely means that we are at the end of the log file.
1039 // Record it and CHECK that in the rest of the log file, we don't find
1040 // any more data on that channel. Not all channels will end at the
1041 // same point in time since they can be in different files.
1042 VLOG(1) << "Found the last message on channel "
1043 << timestamped_message.channel_index << ", "
1044 << configuration::CleanedChannelToString(
1045 logged_configuration()->channels()->Get(
1046 timestamped_message.channel_index))
1047 << " on node " << MaybeNodeName(state->event_loop()->node())
1048 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -08001049
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001050 // The user might be working with log files from 1 node but forgot to
1051 // configure the infrastructure to log data for a remote channel on
1052 // that node. That can be very hard to debug, even though the log
1053 // reader is doing the right thing. At least log a warning in that
1054 // case and tell the user what is happening so they can either update
1055 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001056 const std::vector<std::string> logger_nodes =
1057 FindLoggerNodes(log_files_);
1058 if (logger_nodes.size()) {
1059 // We have old logs which don't have the logger nodes logged. In
1060 // that case, we can't be helpful :(
1061 bool data_logged = false;
1062 const Channel *channel = logged_configuration()->channels()->Get(
1063 timestamped_message.channel_index);
1064 for (const std::string &node : logger_nodes) {
1065 data_logged |=
1066 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1067 }
1068 if (!data_logged) {
1069 LOG(WARNING) << "Got a timestamp without any logfiles which "
1070 "could contain data for channel "
1071 << configuration::CleanedChannelToString(channel);
1072 LOG(WARNING) << "Only have logs logged on ["
1073 << absl::StrJoin(logger_nodes, ", ") << "]";
1074 LOG(WARNING)
1075 << "Dropping the rest of the data on "
1076 << state->event_loop()->node()->name()->string_view();
1077 LOG(WARNING)
1078 << "Consider using --skip_missing_forwarding_entries to "
1079 "bypass this, update your config to log it, or add data "
1080 "from one of the nodes it is logged on.";
1081 }
1082 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001083 // Now that we found the end of one channel, artificially stop the
1084 // rest by setting the found_last_message bit. It is confusing when
1085 // part of your data gets replayed but not all. The rest of them will
1086 // get dropped as they are replayed to keep memory usage down.
1087 state->SetFoundLastMessage(true);
1088
1089 // Vector storing if we've seen a nullptr message or not per channel.
1090 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001091 }
1092
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001093 // Make sure that once we have seen the last message on a channel,
1094 // data doesn't start back up again. If the user wants to play
1095 // through events like this, they can set
1096 // --skip_missing_forwarding_entries or ignore_missing_data_.
1097 if (timestamped_message.data == nullptr) {
1098 state->set_last_message(timestamped_message.channel_index);
1099 } else {
1100 if (state->last_message(timestamped_message.channel_index)) {
1101 LOG(FATAL) << "Found missing data in the middle of the log file on "
1102 "channel "
1103 << timestamped_message.channel_index << " "
1104 << configuration::StrippedChannelToString(
1105 logged_configuration()->channels()->Get(
1106 timestamped_message.channel_index))
1107 << " " << timestamped_message << " "
1108 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001109 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001110 }
Austin Schuh92547522019-12-28 14:33:43 -08001111 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001112 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001113 LOG(WARNING)
1114 << "Not sending data from before the start of the log file. "
1115 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1116 .count()
1117 << " start "
1118 << monotonic_start_time(state->node()).time_since_epoch().count()
1119 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001120 }
1121
James Kuszmaula16a7912022-06-17 10:58:12 -07001122 const BootTimestamp next_time = state->MultiThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001123 if (next_time != BootTimestamp::max_time()) {
1124 if (next_time.boot != state->boot_count()) {
1125 VLOG(1) << "Next message for "
1126 << MaybeNodeName(state->event_loop()->node())
1127 << "is on the next boot, " << next_time << " now is "
1128 << state->monotonic_now();
1129 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001130 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001131 return;
1132 }
James Kuszmaul09632422022-05-25 15:56:19 -07001133 if (event_loop_factory_ != nullptr) {
1134 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1135 << "wakeup for " << next_time.time << "("
1136 << state->ToDistributedClock(next_time.time)
1137 << " distributed), now is " << state->monotonic_now();
1138 } else {
1139 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1140 << "wakeup for " << next_time.time << ", now is "
1141 << state->monotonic_now();
1142 }
James Kuszmaula16a7912022-06-17 10:58:12 -07001143 // TODO(james): This can result in negative times getting passed-through
1144 // in realtime replay.
Austin Schuh58646e22021-08-23 23:51:46 -07001145 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001146 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001147 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1148 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001149 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001150 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001151 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001152 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001153 // Doesn't apply to single-EventLoop replay since the watchers in question
1154 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001155 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001156 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1157 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001158 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001159 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001160
Austin Schuh2f8fd752020-09-01 22:38:28 -07001161 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1162 << state->event_loop()->context().monotonic_event_time << " now "
1163 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001164 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001165
James Kuszmaula16a7912022-06-17 10:58:12 -07001166 state->SeedSortedMessages();
1167
1168 if (state->SingleThreadedOldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001169 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001170 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1171 if (start_time_ != realtime_clock::min_time) {
1172 state->SetStartTimeFlag(start_time_);
1173 }
1174 if (end_time_ != realtime_clock::max_time) {
1175 state->SetEndTimeFlag(end_time_);
1176 }
Austin Schuh58646e22021-08-23 23:51:46 -07001177 event_loop->OnRun([state]() {
James Kuszmaula16a7912022-06-17 10:58:12 -07001178 BootTimestamp next_time = state->SingleThreadedOldestMessageTime();
Austin Schuh58646e22021-08-23 23:51:46 -07001179 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaula16a7912022-06-17 10:58:12 -07001180 // Queue up messages and then set clock offsets (we don't want to set
1181 // clock offsets before we've done the work of getting the first messages
1182 // primed).
1183 state->QueueThreadUntil(
1184 next_time + std::chrono::duration_cast<std::chrono::nanoseconds>(
1185 std::chrono::duration<double>(
1186 FLAGS_threaded_look_ahead_seconds)));
James Kuszmaul09632422022-05-25 15:56:19 -07001187 state->SetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001188 state->Setup(next_time.time);
1189 state->SetupStartupTimer();
1190 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001191 }
1192}
1193
Austin Schuhe33c08d2022-02-03 18:15:21 -08001194void LogReader::SetEndTime(std::string end_time) {
1195 if (end_time.empty()) {
1196 SetEndTime(realtime_clock::max_time);
1197 } else {
1198 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1199 aos::realtime_clock::FromString(end_time);
1200 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1201 << "'. Expected a date in the format of "
1202 "2021-01-15_15-30-35.000000000.";
1203 SetEndTime(*parsed_end_time);
1204 }
1205}
1206
1207void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1208 end_time_ = end_time;
1209}
1210
1211void LogReader::SetStartTime(std::string start_time) {
1212 if (start_time.empty()) {
1213 SetStartTime(realtime_clock::min_time);
1214 } else {
1215 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1216 aos::realtime_clock::FromString(start_time);
1217 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1218 << "'. Expected a date in the format of "
1219 "2021-01-15_15-30-35.000000000.";
1220 SetStartTime(*parsed_start_time);
1221 }
1222}
1223
1224void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1225 start_time_ = start_time;
1226}
1227
Austin Schuhe309d2a2019-11-29 13:25:21 -08001228void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001229 // Make sure that things get destroyed in the correct order, rather than
1230 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001231 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001232 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001233 }
Austin Schuh92547522019-12-28 14:33:43 -08001234
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001235 event_loop_factory_unique_ptr_.reset();
1236 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001237}
1238
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001239void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001240 std::string_view add_prefix,
1241 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001242 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1243 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1244 if (channel->name()->str() == name &&
1245 channel->type()->string_view() == type) {
1246 CHECK_EQ(0u, remapped_channels_.count(ii))
1247 << "Already remapped channel "
1248 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001249 RemappedChannel remapped_channel;
1250 remapped_channel.remapped_name =
1251 std::string(add_prefix) + std::string(name);
1252 remapped_channel.new_type = new_type;
1253 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001254 VLOG(1) << "Remapping channel "
1255 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001256 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001257 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001258 return;
1259 }
1260 }
1261 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1262 << type;
1263}
1264
Austin Schuh01b4c352020-09-21 23:09:39 -07001265void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1266 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001267 std::string_view add_prefix,
1268 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001269 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1270 const Channel *remapped_channel =
1271 configuration::GetChannel(logged_configuration(), name, type, "", node);
1272 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1273 << "\", \"type\": \"" << type << "\"}";
1274 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1275 << "\"}";
1276 VLOG(1) << "Remapped "
1277 << aos::configuration::StrippedChannelToString(remapped_channel);
1278
1279 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1280 // we want it to degrade if the heuristics fail to just work.
1281 //
1282 // The easiest way to do this is going to be incredibly specific and verbose.
1283 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1284 // /original/0/spray. Then, create a map from /original/spray to
1285 // /original/0/spray for just the type we were asked for.
1286 if (name != remapped_channel->name()->string_view()) {
1287 MapT new_map;
1288 new_map.match = std::make_unique<ChannelT>();
1289 new_map.match->name = absl::StrCat(add_prefix, name);
1290 new_map.match->type = type;
1291 if (node != nullptr) {
1292 new_map.match->source_node = node->name()->str();
1293 }
1294 new_map.rename = std::make_unique<ChannelT>();
1295 new_map.rename->name =
1296 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1297 maps_.emplace_back(std::move(new_map));
1298 }
1299
1300 const size_t channel_index =
1301 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1302 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1303 << "Already remapped channel "
1304 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001305
1306 RemappedChannel remapped_channel_struct;
1307 remapped_channel_struct.remapped_name =
1308 std::string(add_prefix) +
1309 std::string(remapped_channel->name()->string_view());
1310 remapped_channel_struct.new_type = new_type;
1311 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001312 MakeRemappedConfig();
1313}
1314
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001315void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001316 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001317 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001318 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001319 << ": Can't change the mapping after the events are scheduled.";
1320 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001321 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001322
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001323 // If no remapping occurred and we are using the original config, then there
1324 // is nothing interesting to do here.
1325 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001326 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001327 return;
1328 }
1329 // Config to copy Channel definitions from. Use the specified
1330 // replay_configuration_ if it has been provided.
1331 const Configuration *const base_config = replay_configuration_ == nullptr
1332 ? logged_configuration()
1333 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001334
1335 // Create a config with all the channels, but un-sorted/merged. Collect up
1336 // the schemas while we do this. Call MergeConfiguration to sort everything,
1337 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001338
1339 // This is the builder that we use for the config containing all the new
1340 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001341 flatbuffers::FlatBufferBuilder fbb;
1342 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001343 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001344
1345 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1346 << ": Merging logic needs to be updated when the number of channel "
1347 "fields changes.";
1348
1349 // List of schemas.
1350 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1351 // Make sure our new RemoteMessage schema is in there for old logs without it.
1352 schema_map.insert(std::make_pair(
1353 RemoteMessage::GetFullyQualifiedName(),
1354 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1355 message_bridge::RemoteMessageSchema()))));
1356
1357 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001358 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001359 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001360 base_config, logged_configuration()->channels()->Get(pair.first), "",
1361 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001362 channel_offsets.emplace_back(
1363 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001364
1365 if (c->has_destination_nodes()) {
1366 for (const Connection *connection : *c->destination_nodes()) {
1367 switch (connection->timestamp_logger()) {
1368 case LoggerConfig::LOCAL_LOGGER:
1369 case LoggerConfig::NOT_LOGGED:
1370 // There is no timestamp channel associated with this, so ignore it.
1371 break;
1372
1373 case LoggerConfig::REMOTE_LOGGER:
1374 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1375 // We want to make a split timestamp channel regardless of what type
1376 // of log this used to be. No sense propagating the single
1377 // timestamp channel.
1378
1379 CHECK(connection->has_timestamp_logger_nodes());
1380 for (const flatbuffers::String *timestamp_logger_node :
1381 *connection->timestamp_logger_nodes()) {
1382 const Node *node = configuration::GetNode(
1383 logged_configuration(), timestamp_logger_node->string_view());
1384 message_bridge::ChannelTimestampFinder finder(
1385 logged_configuration(), "log_reader", node);
1386
1387 // We are assuming here that all the maps are setup correctly to
1388 // handle arbitrary timestamps. Apply the maps for this node to
1389 // see what name this ends up with.
1390 std::string name = finder.SplitChannelName(
1391 pair.second.remapped_name, c->type()->str(), connection);
1392 std::string unmapped_name = name;
1393 configuration::HandleMaps(logged_configuration()->maps(), &name,
1394 "aos.message_bridge.RemoteMessage",
1395 node);
1396 CHECK_NE(name, unmapped_name)
1397 << ": Remote timestamp channel was not remapped, this is "
1398 "very fishy";
1399 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1400 fbb.CreateString(name);
1401 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1402 fbb.CreateString("aos.message_bridge.RemoteMessage");
1403 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1404 fbb.CreateString(timestamp_logger_node->string_view());
1405
1406 // Now, build a channel. Don't log it, 2 senders, and match the
1407 // source frequency.
1408 Channel::Builder channel_builder(fbb);
1409 channel_builder.add_name(channel_name_offset);
1410 channel_builder.add_type(channel_type_offset);
1411 channel_builder.add_source_node(source_node_offset);
1412 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1413 channel_builder.add_num_senders(2);
1414 if (c->has_frequency()) {
1415 channel_builder.add_frequency(c->frequency());
1416 }
1417 channel_offsets.emplace_back(channel_builder.Finish());
1418 }
1419 break;
1420 }
1421 }
1422 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001423 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001424
Austin Schuh0de30f32020-12-06 12:44:28 -08001425 // Now reconstruct the original channels, translating types as needed
1426 for (const Channel *c : *base_config->channels()) {
1427 // Search for a mapping channel.
1428 std::string_view new_type = "";
1429 for (auto &pair : remapped_channels_) {
1430 const Channel *const remapped_channel =
1431 logged_configuration()->channels()->Get(pair.first);
1432 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1433 remapped_channel->type()->string_view() == c->type()->string_view()) {
1434 new_type = pair.second.new_type;
1435 break;
1436 }
1437 }
1438
1439 // Copy everything over.
1440 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1441
1442 // Add the schema if it doesn't exist.
1443 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1444 CHECK(c->has_schema());
1445 schema_map.insert(std::make_pair(c->type()->string_view(),
1446 RecursiveCopyFlatBuffer(c->schema())));
1447 }
1448 }
1449
1450 // The MergeConfiguration API takes a vector, not a map. Convert.
1451 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1452 while (!schema_map.empty()) {
1453 schemas.emplace_back(std::move(schema_map.begin()->second));
1454 schema_map.erase(schema_map.begin());
1455 }
1456
1457 // Create the Configuration containing the new channels that we want to add.
1458 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1459 channels_offset =
1460 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1461
1462 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001463 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001464 if (base_config->maps()) {
1465 for (const Map *map : *base_config->maps()) {
1466 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1467 }
1468 }
1469
1470 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001471 for (const MapT &map : maps_) {
1472 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001473 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001474 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001475 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001476 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001477 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001478 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1479 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001480 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001481 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001482 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001483 match_builder.add_name(match_name_offset);
1484 match_builder.add_type(match_type_offset);
1485 if (!map.match->source_node.empty()) {
1486 match_builder.add_source_node(match_source_node_offset);
1487 }
1488 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1489
Austin Schuh0de30f32020-12-06 12:44:28 -08001490 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001491 rename_builder.add_name(rename_name_offset);
1492 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1493
Austin Schuh0de30f32020-12-06 12:44:28 -08001494 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001495 map_builder.add_match(match_offset);
1496 map_builder.add_rename(rename_offset);
1497 map_offsets.emplace_back(map_builder.Finish());
1498 }
1499
Austin Schuh0de30f32020-12-06 12:44:28 -08001500 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1501 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001502
Austin Schuh0de30f32020-12-06 12:44:28 -08001503 // And copy everything else over.
1504 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1505 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1506
1507 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1508 applications_offset =
1509 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1510
1511 // Now insert everything else in unmodified.
1512 ConfigurationBuilder configuration_builder(fbb);
1513 if (!channels_offset.IsNull()) {
1514 configuration_builder.add_channels(channels_offset);
1515 }
1516 if (!maps_offsets.IsNull()) {
1517 configuration_builder.add_maps(maps_offsets);
1518 }
1519 if (!nodes_offset.IsNull()) {
1520 configuration_builder.add_nodes(nodes_offset);
1521 }
1522 if (!applications_offset.IsNull()) {
1523 configuration_builder.add_applications(applications_offset);
1524 }
1525
1526 if (base_config->has_channel_storage_duration()) {
1527 configuration_builder.add_channel_storage_duration(
1528 base_config->channel_storage_duration());
1529 }
1530
1531 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1532 << ": Merging logic needs to be updated when the number of configuration "
1533 "fields changes.";
1534
1535 fbb.Finish(configuration_builder.Finish());
1536
1537 // Clean it up and return it! By using MergeConfiguration here, we'll
1538 // actually get a deduplicated config for free too.
1539 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1540 configuration::MergeConfiguration(
1541 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1542
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001543 remapped_configuration_buffer_ =
1544 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001545 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001546
1547 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001548
1549 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001550}
1551
Austin Schuh1c227352021-09-17 12:53:54 -07001552std::vector<const Channel *> LogReader::RemappedChannels() const {
1553 std::vector<const Channel *> result;
1554 result.reserve(remapped_channels_.size());
1555 for (auto &pair : remapped_channels_) {
1556 const Channel *const logged_channel =
1557 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1558
1559 auto channel_iterator = std::lower_bound(
1560 remapped_configuration_->channels()->cbegin(),
1561 remapped_configuration_->channels()->cend(),
1562 std::make_pair(std::string_view(pair.second.remapped_name),
1563 logged_channel->type()->string_view()),
1564 CompareChannels);
1565
1566 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1567 CHECK(EqualsChannels(
1568 *channel_iterator,
1569 std::make_pair(std::string_view(pair.second.remapped_name),
1570 logged_channel->type()->string_view())));
1571 result.push_back(*channel_iterator);
1572 }
1573 return result;
1574}
1575
Austin Schuh6f3babe2020-01-26 20:34:50 -08001576const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001577 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001578 const Channel *channel) {
1579 std::string_view channel_name = channel->name()->string_view();
1580 std::string_view channel_type = channel->type()->string_view();
1581 const int channel_index =
1582 configuration::ChannelIndex(logged_configuration(), channel);
1583 // If the channel is remapped, find the correct channel name to use.
1584 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001585 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001586 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001587 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001588 }
1589
Austin Schuhee711052020-08-24 16:06:09 -07001590 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001591 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001592 configuration(), channel_name, channel_type,
1593 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001594
1595 CHECK(remapped_channel != nullptr)
1596 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1597 << channel_type << "\"} because it is not in the provided configuration.";
1598
1599 return remapped_channel;
1600}
1601
James Kuszmaul09632422022-05-25 15:56:19 -07001602LogReader::State::State(
1603 std::unique_ptr<TimestampMapper> timestamp_mapper,
1604 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
James Kuszmaula16a7912022-06-17 10:58:12 -07001605 const Node *node, LogReader::State::ThreadedBuffering threading)
James Kuszmaul09632422022-05-25 15:56:19 -07001606 : timestamp_mapper_(std::move(timestamp_mapper)),
1607 node_(node),
James Kuszmaula16a7912022-06-17 10:58:12 -07001608 multinode_filters_(multinode_filters),
1609 threading_(threading) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001610
1611void LogReader::State::AddPeer(State *peer) {
1612 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1613 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1614 }
1615}
Austin Schuh858c9f32020-08-31 16:56:12 -07001616
Austin Schuh58646e22021-08-23 23:51:46 -07001617void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001618 NodeEventLoopFactory *node_event_loop_factory,
1619 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001620 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001621 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001622}
1623
1624void LogReader::State::SetChannelCount(size_t count) {
1625 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001626 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001627 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001628 channel_source_state_.resize(count);
1629 factory_channel_index_.resize(count);
1630 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001631}
1632
Austin Schuh58646e22021-08-23 23:51:46 -07001633void LogReader::State::SetRemoteTimestampSender(
1634 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1635 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1636}
1637
Austin Schuh858c9f32020-08-31 16:56:12 -07001638void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001639 size_t logged_channel_index, size_t factory_channel_index,
1640 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001641 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1642 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001643 channels_[logged_channel_index] = std::move(sender);
1644 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001645 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001646
Austin Schuh58646e22021-08-23 23:51:46 -07001647 if (is_forwarded) {
1648 queue_index_map_[logged_channel_index] =
1649 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001650 }
1651
1652 factory_channel_index_[logged_channel_index] = factory_channel_index;
1653}
1654
James Kuszmaula16a7912022-06-17 10:58:12 -07001655void LogReader::State::TrackMessageSendTiming(
1656 const RawSender &sender, monotonic_clock::time_point expected_send_time) {
1657 if (event_loop_ == nullptr || !timing_statistics_sender_.valid()) {
1658 return;
1659 }
1660
1661 timing::MessageTimingT sample;
1662 sample.channel = configuration::ChannelIndex(event_loop_->configuration(),
1663 sender.channel());
1664 sample.expected_send_time = expected_send_time.time_since_epoch().count();
1665 sample.actual_send_time =
1666 sender.monotonic_sent_time().time_since_epoch().count();
1667 sample.send_time_error = aos::time::DurationInSeconds(
1668 expected_send_time - sender.monotonic_sent_time());
1669 send_timings_.push_back(sample);
1670
1671 // Somewhat arbitrarily send out timing information in batches of 100. No need
1672 // to create excessive overhead in regenerated logfiles.
1673 // TODO(james): The overhead may be fine.
1674 constexpr size_t kMaxTimesPerStatisticsMessage = 100;
1675 CHECK(timing_statistics_sender_.valid());
1676 if (send_timings_.size() == kMaxTimesPerStatisticsMessage) {
1677 SendMessageTimings();
1678 }
1679}
1680
1681void LogReader::State::SendMessageTimings() {
1682 if (send_timings_.empty() || !timing_statistics_sender_.valid()) {
1683 return;
1684 }
1685 auto builder = timing_statistics_sender_.MakeBuilder();
1686 std::vector<flatbuffers::Offset<timing::MessageTiming>> timing_offsets;
1687 for (const auto &timing : send_timings_) {
1688 timing_offsets.push_back(
1689 timing::MessageTiming::Pack(*builder.fbb(), &timing));
1690 }
1691 send_timings_.clear();
1692 flatbuffers::Offset<
1693 flatbuffers::Vector<flatbuffers::Offset<timing::MessageTiming>>>
1694 timings_offset = builder.fbb()->CreateVector(timing_offsets);
1695 timing::ReplayTiming::Builder timing_builder =
1696 builder.MakeBuilder<timing::ReplayTiming>();
1697 timing_builder.add_messages(timings_offset);
1698 timing_statistics_sender_.CheckOk(builder.Send(timing_builder.Finish()));
1699}
1700
Austin Schuh287d43d2020-12-04 20:19:33 -08001701bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1702 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001703 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001704 uint32_t remote_queue_index = 0xffffffff;
1705
Austin Schuh287d43d2020-12-04 20:19:33 -08001706 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001707 State *source_state =
1708 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001709 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001710 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001711 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001712
Austin Schuh9942bae2021-01-07 22:06:44 -08001713 struct SentTimestamp {
1714 monotonic_clock::time_point monotonic_event_time;
1715 uint32_t queue_index;
1716 } search;
1717
Austin Schuh58646e22021-08-23 23:51:46 -07001718 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1719 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001720 search.monotonic_event_time =
1721 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001722 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001723
1724 // Find the sent time if available.
1725 auto element = std::lower_bound(
1726 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001727 [](ContiguousSentTimestamp a, SentTimestamp b) {
1728 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001729 return true;
1730 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001731 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001732 return false;
1733 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001734
1735 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001736 return true;
1737 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001738 if (a.starting_queue_index >= b.queue_index) {
1739 return false;
1740 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001741
Austin Schuh9942bae2021-01-07 22:06:44 -08001742 // If it isn't clearly below or above, it is below. Since we return
1743 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001744 return false;
1745 });
1746
1747 // TODO(austin): Be a bit more principled here, but we will want to do that
1748 // after the logger rewrite. We hit this when one node finishes, but the
1749 // other node isn't done yet. So there is no send time, but there is a
1750 // receive time.
1751 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001752 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1753 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001754
1755 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001756 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001757 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001758 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001759 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001760 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001761 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001762 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001763
Austin Schuh58646e22021-08-23 23:51:46 -07001764 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001765 element->actual_queue_index -
1766 element->starting_queue_index;
1767 } else {
1768 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001769 }
Austin Schuh58646e22021-08-23 23:51:46 -07001770 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1771 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001772 }
1773
James Kuszmaul09632422022-05-25 15:56:19 -07001774 if (event_loop_factory_ != nullptr &&
1775 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1776 multinode_filters_ != nullptr) {
1777 // Sanity check that we are using consistent boot uuids.
1778 State *source_state =
1779 channel_source_state_[timestamped_message.channel_index];
1780 CHECK_EQ(multinode_filters_->boot_uuid(
1781 configuration::GetNodeIndex(event_loop_->configuration(),
1782 source_state->node()),
1783 timestamped_message.monotonic_remote_time.boot),
1784 CHECK_NOTNULL(
1785 CHECK_NOTNULL(
1786 channel_source_state_[timestamped_message.channel_index])
1787 ->event_loop_)
1788 ->boot_uuid());
1789 }
1790
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001791 // Send! Use the replayed queue index here instead of the logged queue index
1792 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001793 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001794 RawSender::SharedSpan(timestamped_message.data,
1795 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001796 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001797 timestamped_message.realtime_remote_time, remote_queue_index,
1798 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001799 ? CHECK_NOTNULL(multinode_filters_)
1800 ->boot_uuid(configuration::GetNodeIndex(
1801 event_loop_->configuration(),
1802 channel_source_state_[timestamped_message
1803 .channel_index]
1804 ->node()),
1805 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001806 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001807 if (err != RawSender::Error::kOk) return false;
James Kuszmaula16a7912022-06-17 10:58:12 -07001808 if (monotonic_start_time(timestamped_message.monotonic_event_time.boot) <=
1809 timestamped_message.monotonic_event_time.time) {
1810 // Only track errors for non-fetched messages.
1811 TrackMessageSendTiming(
1812 *sender,
1813 timestamped_message.monotonic_event_time.time + clock_offset());
1814 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001815
Austin Schuh287d43d2020-12-04 20:19:33 -08001816 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001817 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001818 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1819 // Nothing here, start a range with 0 length.
1820 ContiguousSentTimestamp timestamp;
1821 timestamp.starting_monotonic_event_time =
1822 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001823 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001824 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001825 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001826 timestamp.actual_queue_index = sender->sent_queue_index();
1827 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1828 timestamp);
1829 } else {
1830 // We've got something. See if the next timestamp is still contiguous. If
1831 // so, grow it.
1832 ContiguousSentTimestamp *back =
1833 &queue_index_map_[timestamped_message.channel_index]->back();
1834 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001835 (timestamped_message.queue_index.index -
1836 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001837 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001838 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001839 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001840 } else {
1841 // Otherwise, make a new one.
1842 ContiguousSentTimestamp timestamp;
1843 timestamp.starting_monotonic_event_time =
1844 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001845 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001846 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001847 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001848 timestamp.actual_queue_index = sender->sent_queue_index();
1849 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1850 timestamp);
1851 }
1852 }
1853
1854 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1855 // queue index diverge a couple of elements, which would be a very small
1856 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001857 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1858 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07001859 // TODO(james): Currently, If running replay against a single event loop,
1860 // remote timestamps will not get replayed because this code-path only
1861 // gets triggered on the event loop that receives the forwarded message
1862 // that the timestamps correspond to. This code, as written, also doesn't
1863 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07001864 State *source_state =
1865 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1866
Austin Schuh969cd602021-01-03 00:09:45 -08001867 flatbuffers::FlatBufferBuilder fbb;
1868 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001869 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1870 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001871
Austin Schuh969cd602021-01-03 00:09:45 -08001872 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001873
1874 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001875 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001876
1877 // Swap the remote and sent metrics. They are from the sender's
1878 // perspective, not the receiver's perspective.
1879 message_header_builder.add_monotonic_sent_time(
1880 sender->monotonic_sent_time().time_since_epoch().count());
1881 message_header_builder.add_realtime_sent_time(
1882 sender->realtime_sent_time().time_since_epoch().count());
1883 message_header_builder.add_queue_index(sender->sent_queue_index());
1884
Austin Schuh58646e22021-08-23 23:51:46 -07001885 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1886 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001887 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001888 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1889 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001890 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001891 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001892
1893 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001894 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001895
Austin Schuh969cd602021-01-03 00:09:45 -08001896 fbb.Finish(message_header_builder.Finish());
1897
1898 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1899 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001900 timestamped_message.monotonic_timestamp_time,
1901 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001902 }
1903
1904 return true;
1905}
1906
Austin Schuh969cd602021-01-03 00:09:45 -08001907LogReader::RemoteMessageSender::RemoteMessageSender(
1908 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1909 : event_loop_(event_loop),
1910 sender_(std::move(sender)),
1911 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1912
1913void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1914 if (remote_timestamps_.empty()) {
1915 CHECK_NOTNULL(timer_);
1916 timer_->Disable();
1917 scheduled_time_ = monotonic_clock::min_time;
1918 return;
1919 }
1920
1921 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1922 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001923 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001924 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001925 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1926 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001927 }
1928}
1929
1930void LogReader::RemoteMessageSender::Send(
1931 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001932 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001933 // There are 2 variants of logs.
1934 // 1) Logs without monotonic_timestamp_time
1935 // 2) Logs with monotonic_timestamp_time
1936 //
1937 // As of Jan 2021, we shouldn't have any more logs without
1938 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1939 // the effort of saving.
1940 //
1941 // This gives us 3 cases, 2 of which are undistinguishable.
1942 // 1) Old log without monotonic_timestamp_time.
1943 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1944 // remotely so we actually have monotonic_timestamp_time.
1945 // 3) New log, but the timestamp was logged on the node receiving the message
1946 // so there is no monotonic_timestamp_time.
1947 //
1948 // Our goal when replaying is to accurately reproduce the state of the world
1949 // present when logging. If a timestamp wasn't sent back across the network,
1950 // we shouldn't replay one back across the network.
1951 //
1952 // Given that we don't really care about 1, we can use the presence of the
1953 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1954 // monotonic_timestamp_time, this means the message was logged locally and
1955 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001956 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001957 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001958 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001959
Austin Schuh58646e22021-08-23 23:51:46 -07001960 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
1961
Austin Schuhc41d6a82021-07-16 14:49:23 -07001962 remote_timestamps_.emplace(
1963 std::upper_bound(
1964 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07001965 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07001966 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1967 const Timestamp &timestamp) {
1968 return monotonic_timestamp_time <
1969 timestamp.monotonic_timestamp_time;
1970 }),
Austin Schuh58646e22021-08-23 23:51:46 -07001971 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07001972 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001973}
1974
1975void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001976 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1977 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001978 CHECK(!remote_timestamps_.empty());
1979
1980 // Send out all timestamps at the currently scheduled time.
1981 while (remote_timestamps_.front().monotonic_timestamp_time ==
1982 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07001983 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
1984 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08001985 remote_timestamps_.pop_front();
1986 if (remote_timestamps_.empty()) {
1987 break;
1988 }
1989 }
1990 scheduled_time_ = monotonic_clock::min_time;
1991
1992 ScheduleTimestamp();
1993}
1994
1995LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001996 const Channel *channel, const Connection *connection) {
1997 message_bridge::ChannelTimestampFinder finder(event_loop_);
1998 // Look at any pre-created channel/connection pairs.
1999 {
2000 auto it =
2001 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
2002 if (it != channel_timestamp_loggers_.end()) {
2003 return it->second.get();
2004 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002005 }
2006
Austin Schuh61e973f2021-02-21 21:43:56 -08002007 // That failed, so resolve the RemoteMessage channel timestamps will be logged
2008 // to.
2009 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
2010
2011 {
2012 // See if that has been created before. If so, cache it in
2013 // channel_timestamp_loggers_ and return.
2014 auto it = timestamp_loggers_.find(timestamp_channel);
2015 if (it != timestamp_loggers_.end()) {
2016 CHECK(channel_timestamp_loggers_
2017 .try_emplace(std::make_pair(channel, connection), it->second)
2018 .second);
2019 return it->second.get();
2020 }
2021 }
2022
2023 // Otherwise, make a sender, save it, and cache it.
2024 auto result = channel_timestamp_loggers_.try_emplace(
2025 std::make_pair(channel, connection),
2026 std::make_shared<RemoteMessageSender>(
2027 event_loop()->MakeSender<RemoteMessage>(
2028 timestamp_channel->name()->string_view()),
2029 event_loop()));
2030
2031 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
2032 .second);
2033 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002034}
2035
Austin Schuhdda74ec2021-01-03 19:30:37 -08002036TimestampedMessage LogReader::State::PopOldest() {
James Kuszmaula16a7912022-06-17 10:58:12 -07002037 if (message_queuer_.has_value()) {
2038 std::optional<TimestampedMessage> message = message_queuer_->Pop();
2039 CHECK(message.has_value()) << ": Unexpectedly ran out of messages.";
2040 message_queuer_->SetState(
2041 message.value().monotonic_event_time +
2042 std::chrono::duration_cast<std::chrono::nanoseconds>(
2043 std::chrono::duration<double>(FLAGS_threaded_look_ahead_seconds)));
2044 return message.value();
2045 } else {
2046 CHECK(timestamp_mapper_ != nullptr);
2047 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2048 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002049
James Kuszmaula16a7912022-06-17 10:58:12 -07002050 TimestampedMessage result = std::move(*result_ptr);
Austin Schuhe639ea12021-01-25 13:00:22 -08002051
James Kuszmaula16a7912022-06-17 10:58:12 -07002052 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
2053 << result.monotonic_event_time;
2054 timestamp_mapper_->PopFront();
2055 SeedSortedMessages();
Austin Schuh858c9f32020-08-31 16:56:12 -07002056
James Kuszmaula16a7912022-06-17 10:58:12 -07002057 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002058
James Kuszmaula16a7912022-06-17 10:58:12 -07002059 VLOG(1) << "Popped " << result
2060 << configuration::CleanedChannelToString(
2061 event_loop_->configuration()->channels()->Get(
2062 factory_channel_index_[result.channel_index]));
2063 return result;
2064 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002065}
2066
James Kuszmaula16a7912022-06-17 10:58:12 -07002067BootTimestamp LogReader::State::MultiThreadedOldestMessageTime() {
2068 if (!message_queuer_.has_value()) {
2069 return SingleThreadedOldestMessageTime();
2070 }
2071 std::optional<TimestampedMessage> message = message_queuer_->Peek();
2072 if (!message.has_value()) {
2073 return BootTimestamp::max_time();
2074 }
2075 if (message.value().monotonic_event_time.boot == boot_count()) {
2076 ObserveNextMessage(message.value().monotonic_event_time.time,
2077 message.value().realtime_event_time);
2078 }
2079 return message.value().monotonic_event_time;
2080}
2081
2082BootTimestamp LogReader::State::SingleThreadedOldestMessageTime() {
2083 CHECK(!message_queuer_.has_value())
2084 << "Cannot use SingleThreadedOldestMessageTime() once the queuer thread "
2085 "is created.";
Austin Schuhe639ea12021-01-25 13:00:22 -08002086 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002087 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08002088 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002089 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2090 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07002091 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08002092 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08002093 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07002094 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08002095 if (result_ptr->monotonic_event_time.boot == boot_count()) {
2096 ObserveNextMessage(result_ptr->monotonic_event_time.time,
2097 result_ptr->realtime_event_time);
2098 }
Austin Schuh58646e22021-08-23 23:51:46 -07002099 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002100}
2101
2102void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002103 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002104
Austin Schuhe639ea12021-01-25 13:00:22 -08002105 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2106 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002107}
2108
2109void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07002110 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08002111 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07002112 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002113 for (size_t i = 0; i < channels_.size(); ++i) {
2114 channels_[i].reset();
2115 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08002116 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08002117 channel_timestamp_loggers_.clear();
2118 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002119 event_loop_unique_ptr_.reset();
2120 event_loop_ = nullptr;
2121 timer_handler_ = nullptr;
2122 node_event_loop_factory_ = nullptr;
James Kuszmaula16a7912022-06-17 10:58:12 -07002123 timing_statistics_sender_ = Sender<timing::ReplayTiming>();
Austin Schuh858c9f32020-08-31 16:56:12 -07002124}
2125
Austin Schuhe33c08d2022-02-03 18:15:21 -08002126void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
2127 if (start_time != realtime_clock::min_time) {
2128 start_event_notifier_ = std::make_unique<EventNotifier>(
2129 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
2130 }
2131}
2132
2133void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
2134 if (end_time != realtime_clock::max_time) {
2135 end_event_notifier_ = std::make_unique<EventNotifier>(
2136 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
2137 }
2138}
2139
2140void LogReader::State::ObserveNextMessage(
2141 monotonic_clock::time_point monotonic_event,
2142 realtime_clock::time_point realtime_event) {
2143 if (start_event_notifier_) {
2144 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2145 }
2146 if (end_event_notifier_) {
2147 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2148 }
2149}
2150
2151void LogReader::State::ClearTimeFlags() {
2152 start_event_notifier_.reset();
2153 end_event_notifier_.reset();
2154}
2155
2156void LogReader::State::NotifyLogfileStart() {
2157 if (start_event_notifier_) {
2158 if (start_event_notifier_->realtime_event_time() >
2159 realtime_start_time(boot_count())) {
2160 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2161 << " > " << realtime_start_time(boot_count());
2162 return;
2163 }
2164 }
2165 if (found_last_message_) {
2166 VLOG(1) << "Last message already found, bailing";
2167 return;
2168 }
2169 RunOnStart();
2170}
2171
2172void LogReader::State::NotifyFlagStart() {
2173 if (start_event_notifier_->realtime_event_time() >=
2174 realtime_start_time(boot_count())) {
2175 RunOnStart();
2176 }
2177}
2178
2179void LogReader::State::NotifyLogfileEnd() {
2180 if (found_last_message_) {
2181 return;
2182 }
2183
2184 if (!stopped_ && started_) {
2185 RunOnEnd();
2186 }
2187}
2188
2189void LogReader::State::NotifyFlagEnd() {
2190 if (!stopped_ && started_) {
2191 RunOnEnd();
2192 SetFoundLastMessage(true);
2193 }
2194}
2195
James Kuszmaul09632422022-05-25 15:56:19 -07002196void LogReader::State::SetClockOffset() {
2197 if (node_event_loop_factory_ == nullptr) {
2198 // If not running with simulated event loop, set the monotonic clock
2199 // offset.
2200 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2201
2202 if (start_event_notifier_) {
2203 start_event_notifier_->SetClockOffset(clock_offset_);
2204 }
2205 if (end_event_notifier_) {
2206 end_event_notifier_->SetClockOffset(clock_offset_);
2207 }
2208 }
2209}
2210
Austin Schuhe309d2a2019-11-29 13:25:21 -08002211} // namespace logger
2212} // namespace aos