blob: a4d6cd0018999ac5fe670abe63f44ae6c2cb24da [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
Austin Schuhe309d2a2019-11-29 13:25:21 -080056namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070057namespace configuration {
58// We don't really want to expose this publicly, but log reader doesn't really
59// want to re-implement it.
60void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
61 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070062} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080063namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070064namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080065
Austin Schuh1c227352021-09-17 12:53:54 -070066bool CompareChannels(const Channel *c,
67 ::std::pair<std::string_view, std::string_view> p) {
68 int name_compare = c->name()->string_view().compare(p.first);
69 if (name_compare == 0) {
70 return c->type()->string_view() < p.second;
71 } else if (name_compare < 0) {
72 return true;
73 } else {
74 return false;
75 }
76}
77
78bool EqualsChannels(const Channel *c,
79 ::std::pair<std::string_view, std::string_view> p) {
80 return c->name()->string_view() == p.first &&
81 c->type()->string_view() == p.second;
82}
83
Austin Schuh0de30f32020-12-06 12:44:28 -080084// Copies the channel, removing the schema as we go. If new_name is provided,
85// it is used instead of the name inside the channel. If new_type is provided,
86// it is used instead of the type in the channel.
87flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
88 std::string_view new_name,
89 std::string_view new_type,
90 flatbuffers::FlatBufferBuilder *fbb) {
91 flatbuffers::Offset<flatbuffers::String> name_offset =
92 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
93 : new_name);
94 flatbuffers::Offset<flatbuffers::String> type_offset =
95 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
96 flatbuffers::Offset<flatbuffers::String> source_node_offset =
97 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
98 : 0;
99
100 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
101 destination_nodes_offset =
102 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
103
104 flatbuffers::Offset<
105 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
106 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
107
108 Channel::Builder channel_builder(*fbb);
109 channel_builder.add_name(name_offset);
110 channel_builder.add_type(type_offset);
111 if (c->has_frequency()) {
112 channel_builder.add_frequency(c->frequency());
113 }
114 if (c->has_max_size()) {
115 channel_builder.add_max_size(c->max_size());
116 }
117 if (c->has_num_senders()) {
118 channel_builder.add_num_senders(c->num_senders());
119 }
120 if (c->has_num_watchers()) {
121 channel_builder.add_num_watchers(c->num_watchers());
122 }
123 if (!source_node_offset.IsNull()) {
124 channel_builder.add_source_node(source_node_offset);
125 }
126 if (!destination_nodes_offset.IsNull()) {
127 channel_builder.add_destination_nodes(destination_nodes_offset);
128 }
129 if (c->has_logger()) {
130 channel_builder.add_logger(c->logger());
131 }
132 if (!logger_nodes_offset.IsNull()) {
133 channel_builder.add_logger_nodes(logger_nodes_offset);
134 }
135 if (c->has_read_method()) {
136 channel_builder.add_read_method(c->read_method());
137 }
138 if (c->has_num_readers()) {
139 channel_builder.add_num_readers(c->num_readers());
140 }
141 return channel_builder.Finish();
142}
143
Austin Schuhe309d2a2019-11-29 13:25:21 -0800144namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800145using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700146} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800147
Austin Schuhe33c08d2022-02-03 18:15:21 -0800148// Class to manage triggering events on the RT clock while replaying logs. Since
149// the RT clock can only change when we get a message, we only need to update
150// our timers when new messages are read.
151class EventNotifier {
152 public:
153 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
154 std::string_view name,
155 realtime_clock::time_point realtime_event_time)
156 : event_loop_(event_loop),
157 fn_(std::move(fn)),
158 realtime_event_time_(realtime_event_time) {
159 CHECK(event_loop_);
160 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
161
162 if (event_loop_->node() != nullptr) {
163 event_timer_->set_name(
164 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
165 } else {
166 event_timer_->set_name(name);
167 }
168 }
169
170 ~EventNotifier() { event_timer_->Disable(); }
171
James Kuszmaul09632422022-05-25 15:56:19 -0700172 // Sets the clock offset for realtime playback.
173 void SetClockOffset(std::chrono::nanoseconds clock_offset) {
174 clock_offset_ = clock_offset;
175 }
176
Austin Schuhe33c08d2022-02-03 18:15:21 -0800177 // Returns the event trigger time.
178 realtime_clock::time_point realtime_event_time() const {
179 return realtime_event_time_;
180 }
181
182 // Observes the next message and potentially calls the callback or updates the
183 // timer.
184 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
185 realtime_clock::time_point realtime_message_time) {
186 if (realtime_message_time < realtime_event_time_) {
187 return;
188 }
189 if (called_) {
190 return;
191 }
192
193 // Move the callback wakeup time to the correct time (or make it now if
194 // there's a gap in time) now that we know it is before the next
195 // message.
196 const monotonic_clock::time_point candidate_monotonic =
197 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
198 const monotonic_clock::time_point monotonic_now =
199 event_loop_->monotonic_now();
200 if (candidate_monotonic < monotonic_now) {
201 // Whops, time went backwards. Just do it now.
202 HandleTime();
203 } else {
James Kuszmaul09632422022-05-25 15:56:19 -0700204 event_timer_->Setup(candidate_monotonic + clock_offset_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800205 }
206 }
207
208 private:
209 void HandleTime() {
210 if (!called_) {
211 called_ = true;
212 fn_();
213 }
214 }
215
216 EventLoop *event_loop_ = nullptr;
217 TimerHandler *event_timer_ = nullptr;
218 std::function<void()> fn_;
219
220 const realtime_clock::time_point realtime_event_time_ =
221 realtime_clock::min_time;
222
James Kuszmaul09632422022-05-25 15:56:19 -0700223 std::chrono::nanoseconds clock_offset_{0};
224
Austin Schuhe33c08d2022-02-03 18:15:21 -0800225 bool called_ = false;
226};
227
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800228LogReader::LogReader(std::string_view filename,
229 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800230 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800231
Austin Schuh287d43d2020-12-04 20:19:33 -0800232LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800233 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800234 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800235 replay_configuration_(replay_configuration) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800236 SetStartTime(FLAGS_start_time);
237 SetEndTime(FLAGS_end_time);
238
Austin Schuh0ca51f32020-12-25 21:51:45 -0800239 CHECK_GT(log_files_.size(), 0u);
240 {
241 // Validate that we have the same config everwhere. This will be true if
242 // all the parts were sorted together and the configs match.
243 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800244 for (const LogFile &log_file : log_files_) {
245 if (log_file.config.get() == nullptr) {
246 LOG(FATAL) << "Couldn't find a config in " << log_file;
247 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800248 if (config == nullptr) {
249 config = log_file.config.get();
250 } else {
251 CHECK_EQ(config, log_file.config.get());
252 }
253 }
254 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800255
Austin Schuh6331ef92020-01-07 18:28:09 -0800256 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800257
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700258 // Remap all existing remote timestamp channels. They will be recreated, and
259 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700260 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800261 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
262 "log_reader", node);
263
264 absl::btree_set<std::string_view> remote_nodes;
265
266 for (const Channel *channel : *logged_configuration()->channels()) {
267 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
268 continue;
269 }
270 if (!channel->has_destination_nodes()) {
271 continue;
272 }
273 for (const Connection *connection : *channel->destination_nodes()) {
274 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
275 node)) {
276 // Start by seeing if the split timestamp channels are being used for
277 // this message. If so, remap them.
278 const Channel *timestamp_channel = configuration::GetChannel(
279 logged_configuration(),
280 finder.SplitChannelName(channel, connection),
281 RemoteMessage::GetFullyQualifiedName(), "", node, true);
282
283 if (timestamp_channel != nullptr) {
284 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
285 RemapLoggedChannel<RemoteMessage>(
286 timestamp_channel->name()->string_view(), node);
287 }
288 continue;
289 }
290
291 // Otherwise collect this one up as a node to look for a combined
292 // channel from. It is more efficient to compare nodes than channels.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700293 LOG(WARNING) << "Failed to find channel "
294 << finder.SplitChannelName(channel, connection)
295 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800296 remote_nodes.insert(connection->name()->string_view());
297 }
298 }
299 }
300
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700301 std::vector<const Node *> timestamp_logger_nodes =
302 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800303 for (const std::string_view remote_node : remote_nodes) {
304 const std::string channel = finder.CombinedChannelName(remote_node);
305
Austin Schuh0de30f32020-12-06 12:44:28 -0800306 // See if the log file is an old log with MessageHeader channels in it, or
307 // a newer log with RemoteMessage. If we find an older log, rename the
308 // type too along with the name.
309 if (HasChannel<MessageHeader>(channel, node)) {
310 CHECK(!HasChannel<RemoteMessage>(channel, node))
311 << ": Can't have both a MessageHeader and RemoteMessage remote "
312 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800313 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
314 // careful about updating the config, but there are fewer and fewer logs
315 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800316 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
317 "aos.message_bridge.RemoteMessage");
318 } else {
319 CHECK(HasChannel<RemoteMessage>(channel, node))
320 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
321 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
322 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800323 // Only bother to remap if there's something on the channel. We can
324 // tell if the channel was marked NOT_LOGGED or not. This makes the
325 // config not change un-necesarily when we replay a log with NOT_LOGGED
326 // messages.
327 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
328 RemapLoggedChannel<RemoteMessage>(channel, node);
329 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800330 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700331 }
332 }
333
Austin Schuh6aa77be2020-02-22 21:06:40 -0800334 if (replay_configuration) {
335 CHECK_EQ(configuration::MultiNode(configuration()),
336 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700337 << ": Log file and replay config need to both be multi or single "
338 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800339 }
340
Austin Schuh6f3babe2020-01-26 20:34:50 -0800341 if (!configuration::MultiNode(configuration())) {
James Kuszmaul09632422022-05-25 15:56:19 -0700342 states_.resize(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800343 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800344 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700345 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800346 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700347 << ": Log file and replay config need to have matching nodes "
348 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700349 for (const Node *node : *logged_configuration()->nodes()) {
350 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700351 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
352 << " in logged config that is not present in the replay "
353 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700354 }
355 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800356 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800357 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800358 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800359}
360
Austin Schuh6aa77be2020-02-22 21:06:40 -0800361LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700362 if (event_loop_factory_unique_ptr_) {
363 Deregister();
364 } else if (event_loop_factory_ != nullptr) {
365 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
366 "is destroyed";
367 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700368 // Zero out some buffers. It's easy to do use-after-frees on these, so make
369 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700370 if (remapped_configuration_buffer_) {
371 remapped_configuration_buffer_->Wipe();
372 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800373}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800374
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800375const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800376 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800377}
378
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800379const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800380 return remapped_configuration_;
381}
382
Austin Schuh07676622021-01-21 18:59:17 -0800383std::vector<const Node *> LogReader::LoggedNodes() const {
384 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800385}
Austin Schuh15649d62019-12-28 16:36:38 -0800386
Austin Schuh11d43732020-09-21 17:28:30 -0700387monotonic_clock::time_point LogReader::monotonic_start_time(
388 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800389 State *state =
390 states_[configuration::GetNodeIndex(configuration(), node)].get();
391 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
392
Austin Schuhf665eb42022-02-03 18:26:25 -0800393 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800394}
395
Austin Schuh11d43732020-09-21 17:28:30 -0700396realtime_clock::time_point LogReader::realtime_start_time(
397 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800398 State *state =
399 states_[configuration::GetNodeIndex(configuration(), node)].get();
400 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
401
Austin Schuhf665eb42022-02-03 18:26:25 -0800402 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800403}
404
Austin Schuh58646e22021-08-23 23:51:46 -0700405void LogReader::OnStart(std::function<void()> fn) {
406 CHECK(!configuration::MultiNode(configuration()));
407 OnStart(nullptr, std::move(fn));
408}
409
410void LogReader::OnStart(const Node *node, std::function<void()> fn) {
411 const int node_index = configuration::GetNodeIndex(configuration(), node);
412 CHECK_GE(node_index, 0);
413 CHECK_LT(node_index, static_cast<int>(states_.size()));
414 State *state = states_[node_index].get();
415 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
416
417 state->OnStart(std::move(fn));
418}
419
420void LogReader::State::OnStart(std::function<void()> fn) {
421 on_starts_.emplace_back(std::move(fn));
422}
423
424void LogReader::State::RunOnStart() {
425 SetRealtimeOffset(monotonic_start_time(boot_count()),
426 realtime_start_time(boot_count()));
427
428 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
429 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800430 auto fn = [this]() {
431 for (size_t i = 0; i < on_starts_.size(); ++i) {
432 on_starts_[i]();
433 }
434 };
435 if (event_loop_factory_) {
436 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
437 } else {
438 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700439 }
440 stopped_ = false;
441 started_ = true;
442}
443
444void LogReader::OnEnd(std::function<void()> fn) {
445 CHECK(!configuration::MultiNode(configuration()));
446 OnEnd(nullptr, std::move(fn));
447}
448
449void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
450 const int node_index = configuration::GetNodeIndex(configuration(), node);
451 CHECK_GE(node_index, 0);
452 CHECK_LT(node_index, static_cast<int>(states_.size()));
453 State *state = states_[node_index].get();
454 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
455
456 state->OnEnd(std::move(fn));
457}
458
459void LogReader::State::OnEnd(std::function<void()> fn) {
460 on_ends_.emplace_back(std::move(fn));
461}
462
463void LogReader::State::RunOnEnd() {
464 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
465 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800466 auto fn = [this]() {
467 for (size_t i = 0; i < on_ends_.size(); ++i) {
468 on_ends_[i]();
469 }
470 };
471 if (event_loop_factory_) {
472 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
473 } else {
474 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700475 }
476
477 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800478 started_ = true;
Austin Schuh58646e22021-08-23 23:51:46 -0700479}
480
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800481void LogReader::Register() {
482 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800483 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800484 Register(event_loop_factory_unique_ptr_.get());
485}
486
Austin Schuh58646e22021-08-23 23:51:46 -0700487void LogReader::RegisterWithoutStarting(
488 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800489 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700490 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800491 filters_ =
492 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800493 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700494 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800495 chrono::duration_cast<chrono::nanoseconds>(
496 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800497
Austin Schuhe639ea12021-01-25 13:00:22 -0800498 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700499 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800500 const size_t node_index =
501 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800502 std::vector<LogParts> filtered_parts = FilterPartsForNode(
503 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800504
Austin Schuh287d43d2020-12-04 20:19:33 -0800505 states_[node_index] = std::make_unique<State>(
506 filtered_parts.size() == 0u
507 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700508 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
James Kuszmaul09632422022-05-25 15:56:19 -0700509 filters_.get(), node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800510 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700511 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800512 event_loop_factory_->GetNodeEventLoopFactory(node),
513 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700514
515 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800516 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800517 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800518 filters_->SetTimestampMappers(std::move(timestamp_mappers));
519
520 // Note: this needs to be set before any times are pulled, or we won't observe
521 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800522 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700523
Austin Schuh287d43d2020-12-04 20:19:33 -0800524 for (const Node *node : configuration::GetNodes(configuration())) {
525 const size_t node_index =
526 configuration::GetNodeIndex(configuration(), node);
527 State *state = states_[node_index].get();
528 for (const Node *other_node : configuration::GetNodes(configuration())) {
529 const size_t other_node_index =
530 configuration::GetNodeIndex(configuration(), other_node);
531 State *other_state = states_[other_node_index].get();
532 if (other_state != state) {
533 state->AddPeer(other_state);
534 }
535 }
536 }
537
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700538 // Register after making all the State objects so we can build references
539 // between them.
540 for (const Node *node : configuration::GetNodes(configuration())) {
541 const size_t node_index =
542 configuration::GetNodeIndex(configuration(), node);
543 State *state = states_[node_index].get();
544
Austin Schuh58646e22021-08-23 23:51:46 -0700545 // If we didn't find any log files with data in them, we won't ever get a
546 // callback or be live. So skip the rest of the setup.
547 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
548 continue;
549 }
550 ++live_nodes_;
551
552 NodeEventLoopFactory *node_factory =
553 event_loop_factory_->GetNodeEventLoopFactory(node);
554 node_factory->OnStartup([this, state, node]() {
555 RegisterDuringStartup(state->MakeEventLoop(), node);
556 });
557 node_factory->OnShutdown([this, state, node]() {
558 RegisterDuringStartup(nullptr, node);
559 state->DestroyEventLoop();
560 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700561 }
562
James Kuszmaul46d82582020-05-09 19:50:09 -0700563 if (live_nodes_ == 0) {
564 LOG(FATAL)
565 << "Don't have logs from any of the nodes in the replay config--are "
566 "you sure that the replay config matches the original config?";
567 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800568
Austin Schuh87dd3832021-01-01 23:07:31 -0800569 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800570
Austin Schuh858c9f32020-08-31 16:56:12 -0700571 for (std::unique_ptr<State> &state : states_) {
572 state->SeedSortedMessages();
573 }
574
Austin Schuh6f3babe2020-01-26 20:34:50 -0800575 // Forwarding is tracked per channel. If it is enabled, we want to turn it
576 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700577 // nodes, and also replayed on the other nodes. This may not satisfy all
578 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800579 if (configuration::MultiNode(event_loop_factory_->configuration())) {
580 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
581 const Channel *channel = logged_configuration()->channels()->Get(i);
582 const Node *node = configuration::GetNode(
583 configuration(), channel->source_node()->string_view());
584
Austin Schuh8bd96322020-02-13 21:18:22 -0800585 State *state =
586 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800587
588 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700589 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800590
591 event_loop_factory_->DisableForwarding(remapped_channel);
592 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700593
594 // If we are replaying a log, we don't want a bunch of redundant messages
595 // from both the real message bridge and simulated message bridge.
596 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800597 }
Austin Schuh891214d2021-11-11 20:35:02 -0800598
599 // Write pseudo start times out to file now that we are all setup.
600 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700601}
602
603void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
604 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800605 StartAfterRegister(event_loop_factory);
606}
607
608void LogReader::StartAfterRegister(
609 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700610 // We want to start the log file at the last start time of the log files
611 // from all the nodes. Compute how long each node's simulation needs to run
612 // to move time to this point.
613 distributed_clock::time_point start_time = distributed_clock::min_time;
614
615 // TODO(austin): We want an "OnStart" callback for each node rather than
616 // running until the last node.
617
618 for (std::unique_ptr<State> &state : states_) {
619 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
620 << " for node " << MaybeNodeName(state->node()) << "now "
621 << state->monotonic_now();
622 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
623 continue;
624 }
625 // And start computing the start time on the distributed clock now that
626 // that works.
627 start_time = std::max(
628 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
629 }
630
631 // TODO(austin): If a node doesn't have a start time, we might not queue
632 // enough. If this happens, we'll explode with a frozen error eventually.
633
634 CHECK_GE(start_time, distributed_clock::epoch())
635 << ": Hmm, we have a node starting before the start of time. Offset "
636 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800637
Austin Schuhcde938c2020-02-02 17:30:07 -0800638 // While we are starting the system up, we might be relying on matching data
639 // to timestamps on log files where the timestamp log file starts before the
640 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800641 {
642 const bool prior_ignore_missing_data = ignore_missing_data_;
643 ignore_missing_data_ = true;
644 VLOG(1) << "Running until " << start_time << " in Register";
645 event_loop_factory_->RunFor(start_time.time_since_epoch());
646 VLOG(1) << "At start time";
647 // Now that we are running for real, missing data means that the log file is
648 // corrupted or went wrong.
649 ignore_missing_data_ = prior_ignore_missing_data;
650 }
Austin Schuh92547522019-12-28 14:33:43 -0800651
Austin Schuh8bd96322020-02-13 21:18:22 -0800652 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700653 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700654 if (state->realtime_start_time(0) != realtime_clock::min_time) {
655 state->SetRealtimeOffset(state->monotonic_start_time(0),
656 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700657 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700658 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
659 << " for node " << MaybeNodeName(state->event_loop()->node())
660 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700661 }
662
663 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800664 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800665 }
666}
667
Austin Schuh2f8fd752020-09-01 22:38:28 -0700668message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800669 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800670 if (filters_) {
671 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800672 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800673 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800674}
675
James Kuszmaul09632422022-05-25 15:56:19 -0700676// TODO(jkuszmaul): Make in-line modifications to
677// ServerStatistics/ClientStatistics messages for ShmEventLoop-based replay to
678// avoid messing up anything that depends on them having valid offsets.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800679void LogReader::Register(EventLoop *event_loop) {
James Kuszmaul09632422022-05-25 15:56:19 -0700680 filters_ =
681 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
682 event_loop->configuration(), logged_configuration(),
683 log_files_[0].boots, FLAGS_skip_order_validation,
684 chrono::duration_cast<chrono::nanoseconds>(
685 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
686
687 std::vector<TimestampMapper *> timestamp_mappers;
688 for (const Node *node : configuration::GetNodes(configuration())) {
689 const size_t node_index =
690 configuration::GetNodeIndex(configuration(), node);
691 std::vector<LogParts> filtered_parts = FilterPartsForNode(
692 log_files_, node != nullptr ? node->name()->string_view() : "");
693
694 states_[node_index] = std::make_unique<State>(
695 filtered_parts.size() == 0u
696 ? nullptr
697 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
698 filters_.get(), node);
699 State *state = states_[node_index].get();
700
701 state->SetChannelCount(logged_configuration()->channels()->size());
702 timestamp_mappers.emplace_back(state->timestamp_mapper());
703 }
704
705 filters_->SetTimestampMappers(std::move(timestamp_mappers));
706
707 for (const Node *node : configuration::GetNodes(configuration())) {
708 const size_t node_index =
709 configuration::GetNodeIndex(configuration(), node);
710 State *state = states_[node_index].get();
711 for (const Node *other_node : configuration::GetNodes(configuration())) {
712 const size_t other_node_index =
713 configuration::GetNodeIndex(configuration(), other_node);
714 State *other_state = states_[other_node_index].get();
715 if (other_state != state) {
716 state->AddPeer(other_state);
717 }
718 }
719 }
720 for (const Node *node : configuration::GetNodes(configuration())) {
721 if (node == nullptr || node->name()->string_view() ==
722 event_loop->node()->name()->string_view()) {
723 Register(event_loop, event_loop->node());
724 } else {
725 Register(nullptr, node);
726 }
727 }
Austin Schuh58646e22021-08-23 23:51:46 -0700728}
729
730void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800731 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700732 states_[configuration::GetNodeIndex(configuration(), node)].get();
733
734 // If we didn't find any log files with data in them, we won't ever get a
735 // callback or be live. So skip the rest of the setup.
736 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
737 return;
738 }
James Kuszmaul09632422022-05-25 15:56:19 -0700739
740 if (event_loop != nullptr) {
741 ++live_nodes_;
742 }
Austin Schuh58646e22021-08-23 23:51:46 -0700743
744 if (event_loop_factory_ != nullptr) {
745 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
746 [this, event_loop, node]() {
747 RegisterDuringStartup(event_loop, node);
748 });
749 } else {
750 RegisterDuringStartup(event_loop, node);
751 }
752}
753
754void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
James Kuszmaul09632422022-05-25 15:56:19 -0700755 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700756 CHECK(event_loop->configuration() == configuration());
757 }
758
759 State *state =
760 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800761
James Kuszmaul09632422022-05-25 15:56:19 -0700762 if (event_loop == nullptr) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800763 state->ClearTimeFlags();
764 }
765
Austin Schuh858c9f32020-08-31 16:56:12 -0700766 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800767
Tyler Chatow67ddb032020-01-12 14:30:04 -0800768 // We don't run timing reports when trying to print out logged data, because
769 // otherwise we would end up printing out the timing reports themselves...
770 // This is only really relevant when we are replaying into a simulation.
James Kuszmaul09632422022-05-25 15:56:19 -0700771 if (event_loop != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -0700772 event_loop->SkipTimingReport();
773 event_loop->SkipAosLog();
774 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800775
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700776 for (size_t logged_channel_index = 0;
777 logged_channel_index < logged_configuration()->channels()->size();
778 ++logged_channel_index) {
779 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700780 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700781 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800782
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700783 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700784 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700785
786 State *source_state = nullptr;
James Kuszmaul09632422022-05-25 15:56:19 -0700787
Austin Schuh58646e22021-08-23 23:51:46 -0700788 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
789 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700790 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700791 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800792
Austin Schuh58646e22021-08-23 23:51:46 -0700793 // We've got a message which is being forwarded to this node.
794 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700795
796 source_state =
797 states_[configuration::GetNodeIndex(configuration(), source_node)]
798 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800799 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700800
Austin Schuh58646e22021-08-23 23:51:46 -0700801 // We are the source, and it is forwarded.
802 const bool is_forwarded =
803 configuration::ChannelIsSendableOnNode(channel, node) &&
804 configuration::ConnectionCount(channel);
805
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700806 state->SetChannel(
807 logged_channel_index,
808 configuration::ChannelIndex(configuration(), channel),
James Kuszmaul09632422022-05-25 15:56:19 -0700809 event_loop && logged &&
810 configuration::ChannelIsReadableOnNode(channel, node)
811 ? event_loop->MakeRawSender(channel)
812 : nullptr,
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700813 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700814
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700815 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700816 const Node *source_node = configuration::GetNode(
817 configuration(), channel->source_node()->string_view());
818
819 for (const Connection *connection : *channel->destination_nodes()) {
820 const bool delivery_time_is_logged =
821 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
822 source_node);
823
824 if (delivery_time_is_logged) {
825 State *destination_state =
826 states_[configuration::GetNodeIndex(
827 configuration(), connection->name()->string_view())]
828 .get();
James Kuszmaul09632422022-05-25 15:56:19 -0700829 if (destination_state) {
830 destination_state->SetRemoteTimestampSender(
831 logged_channel_index,
832 event_loop ? state->RemoteTimestampSender(channel, connection)
833 : nullptr);
834 }
Austin Schuh58646e22021-08-23 23:51:46 -0700835 }
836 }
837 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800838 }
839
Austin Schuh58646e22021-08-23 23:51:46 -0700840 if (!event_loop) {
841 state->ClearRemoteTimestampSenders();
842 state->set_timer_handler(nullptr);
843 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800844 return;
845 }
846
Austin Schuh858c9f32020-08-31 16:56:12 -0700847 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh58646e22021-08-23 23:51:46 -0700848 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800849 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700850 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800851 if (exit_on_finish_ && live_nodes_ == 0) {
James Kuszmaul09632422022-05-25 15:56:19 -0700852 CHECK_NOTNULL(event_loop_factory_)->Exit();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800853 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800854 return;
855 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700856
Austin Schuhdda74ec2021-01-03 19:30:37 -0800857 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700858
859 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
860 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800861
Austin Schuhe309d2a2019-11-29 13:25:21 -0800862 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700863 state->event_loop()->context().monotonic_event_time;
James Kuszmaul09632422022-05-25 15:56:19 -0700864 if (event_loop_factory_ != nullptr) {
865 // Only enforce exact timing in simulation.
866 if (!FLAGS_skip_order_validation) {
867 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
868 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
869 << monotonic_now << " trying to send "
870 << timestamped_message.monotonic_event_time << " failure "
871 << state->DebugString();
872 } else if (BootTimestamp{.boot = state->boot_count(),
873 .time = monotonic_now} !=
874 timestamped_message.monotonic_event_time) {
875 LOG(WARNING) << "Check failed: monotonic_now == "
876 "timestamped_message.monotonic_event_time) ("
877 << monotonic_now << " vs. "
878 << timestamped_message.monotonic_event_time
879 << "): " << FlatbufferToJson(state->event_loop()->node())
880 << " Now " << monotonic_now << " trying to send "
881 << timestamped_message.monotonic_event_time << " failure "
882 << state->DebugString();
883 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700884 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800885
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700886 if (timestamped_message.monotonic_event_time.time >
887 state->monotonic_start_time(
888 timestamped_message.monotonic_event_time.boot) ||
James Kuszmaul09632422022-05-25 15:56:19 -0700889 event_loop_factory_ != nullptr ||
890 !FLAGS_drop_realtime_messages_before_start) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800891 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800892 if (timestamped_message.monotonic_remote_time !=
James Kuszmaul09632422022-05-25 15:56:19 -0700893 BootTimestamp::min_time() &&
894 !FLAGS_skip_order_validation && event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800895 // Confirm that the message was sent on the sending node before the
896 // destination node (this node). As a proxy, do this by making sure
897 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800898 //
899 // TODO(austin): <= means that the cause message (which we know) could
900 // happen after the effect even though we know they are at the same
901 // time. I doubt anyone will notice for a bit, but we should really
902 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -0700903 BootTimestamp monotonic_remote_now =
904 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700905 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -0700906 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -0800907 monotonic_remote_now.boot)
908 << state->event_loop()->node()->name()->string_view() << " to "
909 << state->remote_node(timestamped_message.channel_index)
910 ->name()
911 ->string_view()
912 << " while trying to send a message on "
913 << configuration::CleanedChannelToString(
914 logged_configuration()->channels()->Get(
915 timestamped_message.channel_index))
916 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700917 CHECK_LE(timestamped_message.monotonic_remote_time,
918 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700919 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800920 << state->remote_node(timestamped_message.channel_index)
921 ->name()
922 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800923 << " while trying to send a message on "
924 << configuration::CleanedChannelToString(
925 logged_configuration()->channels()->Get(
926 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700927 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700928 } else if (monotonic_remote_now.boot !=
929 timestamped_message.monotonic_remote_time.boot) {
930 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
931 << " vs "
932 << timestamped_message.monotonic_remote_time.boot;
933 } else if (timestamped_message.monotonic_remote_time >
934 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700935 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800936 << "Check failed: timestamped_message.monotonic_remote_time < "
937 "state->monotonic_remote_now(timestamped_message.channel_"
938 "index) ("
939 << timestamped_message.monotonic_remote_time << " vs. "
940 << state->monotonic_remote_now(
941 timestamped_message.channel_index)
942 << ") " << state->event_loop()->node()->name()->string_view()
943 << " to "
944 << state->remote_node(timestamped_message.channel_index)
945 ->name()
946 ->string_view()
947 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700948 << " ("
949 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700950 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700951 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800952 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700953 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800954 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700955 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700956 << ") " << state->DebugString();
957 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800958 }
959
Austin Schuh15649d62019-12-28 16:36:38 -0800960 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700961 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800962 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800963
Austin Schuh2f8fd752020-09-01 22:38:28 -0700964 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
James Kuszmaul09632422022-05-25 15:56:19 -0700965 << timestamped_message.monotonic_event_time << " "
966 << state->DebugString();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700967 // TODO(austin): std::move channel_data in and make that efficient in
968 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800969 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800970 } else if (state->found_last_message() ||
971 (!ignore_missing_data_ &&
972 // When starting up, we can have data which was sent before
973 // the log starts, but the timestamp was after the log
974 // starts. This is unreasonable to avoid, so ignore the
975 // missing data.
976 timestamped_message.monotonic_remote_time.time >=
977 state->monotonic_remote_start_time(
978 timestamped_message.monotonic_remote_time.boot,
979 timestamped_message.channel_index) &&
980 !FLAGS_skip_missing_forwarding_entries)) {
981 if (!state->found_last_message()) {
982 // We've found a timestamp without data that we expect to have data
983 // for. This likely means that we are at the end of the log file.
984 // Record it and CHECK that in the rest of the log file, we don't find
985 // any more data on that channel. Not all channels will end at the
986 // same point in time since they can be in different files.
987 VLOG(1) << "Found the last message on channel "
988 << timestamped_message.channel_index << ", "
989 << configuration::CleanedChannelToString(
990 logged_configuration()->channels()->Get(
991 timestamped_message.channel_index))
992 << " on node " << MaybeNodeName(state->event_loop()->node())
993 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -0800994
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800995 // The user might be working with log files from 1 node but forgot to
996 // configure the infrastructure to log data for a remote channel on
997 // that node. That can be very hard to debug, even though the log
998 // reader is doing the right thing. At least log a warning in that
999 // case and tell the user what is happening so they can either update
1000 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -07001001 const std::vector<std::string> logger_nodes =
1002 FindLoggerNodes(log_files_);
1003 if (logger_nodes.size()) {
1004 // We have old logs which don't have the logger nodes logged. In
1005 // that case, we can't be helpful :(
1006 bool data_logged = false;
1007 const Channel *channel = logged_configuration()->channels()->Get(
1008 timestamped_message.channel_index);
1009 for (const std::string &node : logger_nodes) {
1010 data_logged |=
1011 configuration::ChannelMessageIsLoggedOnNode(channel, node);
1012 }
1013 if (!data_logged) {
1014 LOG(WARNING) << "Got a timestamp without any logfiles which "
1015 "could contain data for channel "
1016 << configuration::CleanedChannelToString(channel);
1017 LOG(WARNING) << "Only have logs logged on ["
1018 << absl::StrJoin(logger_nodes, ", ") << "]";
1019 LOG(WARNING)
1020 << "Dropping the rest of the data on "
1021 << state->event_loop()->node()->name()->string_view();
1022 LOG(WARNING)
1023 << "Consider using --skip_missing_forwarding_entries to "
1024 "bypass this, update your config to log it, or add data "
1025 "from one of the nodes it is logged on.";
1026 }
1027 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001028 // Now that we found the end of one channel, artificially stop the
1029 // rest by setting the found_last_message bit. It is confusing when
1030 // part of your data gets replayed but not all. The rest of them will
1031 // get dropped as they are replayed to keep memory usage down.
1032 state->SetFoundLastMessage(true);
1033
1034 // Vector storing if we've seen a nullptr message or not per channel.
1035 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -07001036 }
1037
Austin Schuhbd5f74a2021-11-11 20:55:38 -08001038 // Make sure that once we have seen the last message on a channel,
1039 // data doesn't start back up again. If the user wants to play
1040 // through events like this, they can set
1041 // --skip_missing_forwarding_entries or ignore_missing_data_.
1042 if (timestamped_message.data == nullptr) {
1043 state->set_last_message(timestamped_message.channel_index);
1044 } else {
1045 if (state->last_message(timestamped_message.channel_index)) {
1046 LOG(FATAL) << "Found missing data in the middle of the log file on "
1047 "channel "
1048 << timestamped_message.channel_index << " "
1049 << configuration::StrippedChannelToString(
1050 logged_configuration()->channels()->Get(
1051 timestamped_message.channel_index))
1052 << " " << timestamped_message << " "
1053 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -08001054 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001055 }
Austin Schuh92547522019-12-28 14:33:43 -08001056 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001057 } else {
James Kuszmaul09632422022-05-25 15:56:19 -07001058 LOG(WARNING)
1059 << "Not sending data from before the start of the log file. "
1060 << timestamped_message.monotonic_event_time.time.time_since_epoch()
1061 .count()
1062 << " start "
1063 << monotonic_start_time(state->node()).time_since_epoch().count()
1064 << " timestamped_message.data is null";
Austin Schuhe309d2a2019-11-29 13:25:21 -08001065 }
1066
Austin Schuh58646e22021-08-23 23:51:46 -07001067 const BootTimestamp next_time = state->OldestMessageTime();
1068 if (next_time != BootTimestamp::max_time()) {
1069 if (next_time.boot != state->boot_count()) {
1070 VLOG(1) << "Next message for "
1071 << MaybeNodeName(state->event_loop()->node())
1072 << "is on the next boot, " << next_time << " now is "
1073 << state->monotonic_now();
1074 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001075 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001076 return;
1077 }
James Kuszmaul09632422022-05-25 15:56:19 -07001078 if (event_loop_factory_ != nullptr) {
1079 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1080 << "wakeup for " << next_time.time << "("
1081 << state->ToDistributedClock(next_time.time)
1082 << " distributed), now is " << state->monotonic_now();
1083 } else {
1084 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1085 << "wakeup for " << next_time.time << ", now is "
1086 << state->monotonic_now();
1087 }
Austin Schuh58646e22021-08-23 23:51:46 -07001088 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001089 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001090 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1091 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001092 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001093 // Set a timer up immediately after now to die. If we don't do this,
James Kuszmaul09632422022-05-25 15:56:19 -07001094 // then the watchers waiting on the message we just read will never get
Austin Schuh2f8fd752020-09-01 22:38:28 -07001095 // called.
James Kuszmaul09632422022-05-25 15:56:19 -07001096 // Doesn't apply to single-EventLoop replay since the watchers in question
1097 // are not under our control.
Austin Schuheecb9282020-01-08 17:43:30 -08001098 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001099 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1100 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001101 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001102 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001103
Austin Schuh2f8fd752020-09-01 22:38:28 -07001104 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1105 << state->event_loop()->context().monotonic_event_time << " now "
1106 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001107 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001108
Austin Schuh58646e22021-08-23 23:51:46 -07001109 if (state->OldestMessageTime() != BootTimestamp::max_time()) {
1110 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001111 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1112 if (start_time_ != realtime_clock::min_time) {
1113 state->SetStartTimeFlag(start_time_);
1114 }
1115 if (end_time_ != realtime_clock::max_time) {
1116 state->SetEndTimeFlag(end_time_);
1117 }
Austin Schuh58646e22021-08-23 23:51:46 -07001118 event_loop->OnRun([state]() {
1119 BootTimestamp next_time = state->OldestMessageTime();
1120 CHECK_EQ(next_time.boot, state->boot_count());
James Kuszmaul09632422022-05-25 15:56:19 -07001121 state->SetClockOffset();
Austin Schuh58646e22021-08-23 23:51:46 -07001122 state->Setup(next_time.time);
1123 state->SetupStartupTimer();
1124 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001125 }
1126}
1127
Austin Schuhe33c08d2022-02-03 18:15:21 -08001128void LogReader::SetEndTime(std::string end_time) {
1129 if (end_time.empty()) {
1130 SetEndTime(realtime_clock::max_time);
1131 } else {
1132 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1133 aos::realtime_clock::FromString(end_time);
1134 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1135 << "'. Expected a date in the format of "
1136 "2021-01-15_15-30-35.000000000.";
1137 SetEndTime(*parsed_end_time);
1138 }
1139}
1140
1141void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1142 end_time_ = end_time;
1143}
1144
1145void LogReader::SetStartTime(std::string start_time) {
1146 if (start_time.empty()) {
1147 SetStartTime(realtime_clock::min_time);
1148 } else {
1149 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1150 aos::realtime_clock::FromString(start_time);
1151 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1152 << "'. Expected a date in the format of "
1153 "2021-01-15_15-30-35.000000000.";
1154 SetStartTime(*parsed_start_time);
1155 }
1156}
1157
1158void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1159 start_time_ = start_time;
1160}
1161
Austin Schuhe309d2a2019-11-29 13:25:21 -08001162void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001163 // Make sure that things get destroyed in the correct order, rather than
1164 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001165 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001166 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001167 }
Austin Schuh92547522019-12-28 14:33:43 -08001168
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001169 event_loop_factory_unique_ptr_.reset();
1170 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001171}
1172
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001173void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001174 std::string_view add_prefix,
1175 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001176 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1177 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1178 if (channel->name()->str() == name &&
1179 channel->type()->string_view() == type) {
1180 CHECK_EQ(0u, remapped_channels_.count(ii))
1181 << "Already remapped channel "
1182 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001183 RemappedChannel remapped_channel;
1184 remapped_channel.remapped_name =
1185 std::string(add_prefix) + std::string(name);
1186 remapped_channel.new_type = new_type;
1187 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001188 VLOG(1) << "Remapping channel "
1189 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001190 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001191 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001192 return;
1193 }
1194 }
1195 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1196 << type;
1197}
1198
Austin Schuh01b4c352020-09-21 23:09:39 -07001199void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1200 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001201 std::string_view add_prefix,
1202 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001203 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1204 const Channel *remapped_channel =
1205 configuration::GetChannel(logged_configuration(), name, type, "", node);
1206 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1207 << "\", \"type\": \"" << type << "\"}";
1208 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1209 << "\"}";
1210 VLOG(1) << "Remapped "
1211 << aos::configuration::StrippedChannelToString(remapped_channel);
1212
1213 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1214 // we want it to degrade if the heuristics fail to just work.
1215 //
1216 // The easiest way to do this is going to be incredibly specific and verbose.
1217 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1218 // /original/0/spray. Then, create a map from /original/spray to
1219 // /original/0/spray for just the type we were asked for.
1220 if (name != remapped_channel->name()->string_view()) {
1221 MapT new_map;
1222 new_map.match = std::make_unique<ChannelT>();
1223 new_map.match->name = absl::StrCat(add_prefix, name);
1224 new_map.match->type = type;
1225 if (node != nullptr) {
1226 new_map.match->source_node = node->name()->str();
1227 }
1228 new_map.rename = std::make_unique<ChannelT>();
1229 new_map.rename->name =
1230 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1231 maps_.emplace_back(std::move(new_map));
1232 }
1233
1234 const size_t channel_index =
1235 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1236 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1237 << "Already remapped channel "
1238 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001239
1240 RemappedChannel remapped_channel_struct;
1241 remapped_channel_struct.remapped_name =
1242 std::string(add_prefix) +
1243 std::string(remapped_channel->name()->string_view());
1244 remapped_channel_struct.new_type = new_type;
1245 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001246 MakeRemappedConfig();
1247}
1248
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001249void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001250 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001251 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001252 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001253 << ": Can't change the mapping after the events are scheduled.";
1254 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001255 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001256
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001257 // If no remapping occurred and we are using the original config, then there
1258 // is nothing interesting to do here.
1259 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001260 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001261 return;
1262 }
1263 // Config to copy Channel definitions from. Use the specified
1264 // replay_configuration_ if it has been provided.
1265 const Configuration *const base_config = replay_configuration_ == nullptr
1266 ? logged_configuration()
1267 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001268
1269 // Create a config with all the channels, but un-sorted/merged. Collect up
1270 // the schemas while we do this. Call MergeConfiguration to sort everything,
1271 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001272
1273 // This is the builder that we use for the config containing all the new
1274 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001275 flatbuffers::FlatBufferBuilder fbb;
1276 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001277 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001278
1279 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1280 << ": Merging logic needs to be updated when the number of channel "
1281 "fields changes.";
1282
1283 // List of schemas.
1284 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1285 // Make sure our new RemoteMessage schema is in there for old logs without it.
1286 schema_map.insert(std::make_pair(
1287 RemoteMessage::GetFullyQualifiedName(),
1288 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1289 message_bridge::RemoteMessageSchema()))));
1290
1291 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001292 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001293 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001294 base_config, logged_configuration()->channels()->Get(pair.first), "",
1295 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001296 channel_offsets.emplace_back(
1297 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001298
1299 if (c->has_destination_nodes()) {
1300 for (const Connection *connection : *c->destination_nodes()) {
1301 switch (connection->timestamp_logger()) {
1302 case LoggerConfig::LOCAL_LOGGER:
1303 case LoggerConfig::NOT_LOGGED:
1304 // There is no timestamp channel associated with this, so ignore it.
1305 break;
1306
1307 case LoggerConfig::REMOTE_LOGGER:
1308 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1309 // We want to make a split timestamp channel regardless of what type
1310 // of log this used to be. No sense propagating the single
1311 // timestamp channel.
1312
1313 CHECK(connection->has_timestamp_logger_nodes());
1314 for (const flatbuffers::String *timestamp_logger_node :
1315 *connection->timestamp_logger_nodes()) {
1316 const Node *node = configuration::GetNode(
1317 logged_configuration(), timestamp_logger_node->string_view());
1318 message_bridge::ChannelTimestampFinder finder(
1319 logged_configuration(), "log_reader", node);
1320
1321 // We are assuming here that all the maps are setup correctly to
1322 // handle arbitrary timestamps. Apply the maps for this node to
1323 // see what name this ends up with.
1324 std::string name = finder.SplitChannelName(
1325 pair.second.remapped_name, c->type()->str(), connection);
1326 std::string unmapped_name = name;
1327 configuration::HandleMaps(logged_configuration()->maps(), &name,
1328 "aos.message_bridge.RemoteMessage",
1329 node);
1330 CHECK_NE(name, unmapped_name)
1331 << ": Remote timestamp channel was not remapped, this is "
1332 "very fishy";
1333 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1334 fbb.CreateString(name);
1335 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1336 fbb.CreateString("aos.message_bridge.RemoteMessage");
1337 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1338 fbb.CreateString(timestamp_logger_node->string_view());
1339
1340 // Now, build a channel. Don't log it, 2 senders, and match the
1341 // source frequency.
1342 Channel::Builder channel_builder(fbb);
1343 channel_builder.add_name(channel_name_offset);
1344 channel_builder.add_type(channel_type_offset);
1345 channel_builder.add_source_node(source_node_offset);
1346 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1347 channel_builder.add_num_senders(2);
1348 if (c->has_frequency()) {
1349 channel_builder.add_frequency(c->frequency());
1350 }
1351 channel_offsets.emplace_back(channel_builder.Finish());
1352 }
1353 break;
1354 }
1355 }
1356 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001357 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001358
Austin Schuh0de30f32020-12-06 12:44:28 -08001359 // Now reconstruct the original channels, translating types as needed
1360 for (const Channel *c : *base_config->channels()) {
1361 // Search for a mapping channel.
1362 std::string_view new_type = "";
1363 for (auto &pair : remapped_channels_) {
1364 const Channel *const remapped_channel =
1365 logged_configuration()->channels()->Get(pair.first);
1366 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1367 remapped_channel->type()->string_view() == c->type()->string_view()) {
1368 new_type = pair.second.new_type;
1369 break;
1370 }
1371 }
1372
1373 // Copy everything over.
1374 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1375
1376 // Add the schema if it doesn't exist.
1377 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1378 CHECK(c->has_schema());
1379 schema_map.insert(std::make_pair(c->type()->string_view(),
1380 RecursiveCopyFlatBuffer(c->schema())));
1381 }
1382 }
1383
1384 // The MergeConfiguration API takes a vector, not a map. Convert.
1385 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1386 while (!schema_map.empty()) {
1387 schemas.emplace_back(std::move(schema_map.begin()->second));
1388 schema_map.erase(schema_map.begin());
1389 }
1390
1391 // Create the Configuration containing the new channels that we want to add.
1392 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1393 channels_offset =
1394 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1395
1396 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001397 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001398 if (base_config->maps()) {
1399 for (const Map *map : *base_config->maps()) {
1400 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1401 }
1402 }
1403
1404 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001405 for (const MapT &map : maps_) {
1406 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001407 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001408 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001409 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001410 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001411 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001412 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1413 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001414 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001415 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001416 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001417 match_builder.add_name(match_name_offset);
1418 match_builder.add_type(match_type_offset);
1419 if (!map.match->source_node.empty()) {
1420 match_builder.add_source_node(match_source_node_offset);
1421 }
1422 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1423
Austin Schuh0de30f32020-12-06 12:44:28 -08001424 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001425 rename_builder.add_name(rename_name_offset);
1426 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1427
Austin Schuh0de30f32020-12-06 12:44:28 -08001428 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001429 map_builder.add_match(match_offset);
1430 map_builder.add_rename(rename_offset);
1431 map_offsets.emplace_back(map_builder.Finish());
1432 }
1433
Austin Schuh0de30f32020-12-06 12:44:28 -08001434 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1435 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001436
Austin Schuh0de30f32020-12-06 12:44:28 -08001437 // And copy everything else over.
1438 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1439 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1440
1441 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1442 applications_offset =
1443 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1444
1445 // Now insert everything else in unmodified.
1446 ConfigurationBuilder configuration_builder(fbb);
1447 if (!channels_offset.IsNull()) {
1448 configuration_builder.add_channels(channels_offset);
1449 }
1450 if (!maps_offsets.IsNull()) {
1451 configuration_builder.add_maps(maps_offsets);
1452 }
1453 if (!nodes_offset.IsNull()) {
1454 configuration_builder.add_nodes(nodes_offset);
1455 }
1456 if (!applications_offset.IsNull()) {
1457 configuration_builder.add_applications(applications_offset);
1458 }
1459
1460 if (base_config->has_channel_storage_duration()) {
1461 configuration_builder.add_channel_storage_duration(
1462 base_config->channel_storage_duration());
1463 }
1464
1465 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1466 << ": Merging logic needs to be updated when the number of configuration "
1467 "fields changes.";
1468
1469 fbb.Finish(configuration_builder.Finish());
1470
1471 // Clean it up and return it! By using MergeConfiguration here, we'll
1472 // actually get a deduplicated config for free too.
1473 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1474 configuration::MergeConfiguration(
1475 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1476
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001477 remapped_configuration_buffer_ =
1478 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001479 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001480
1481 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001482
1483 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001484}
1485
Austin Schuh1c227352021-09-17 12:53:54 -07001486std::vector<const Channel *> LogReader::RemappedChannels() const {
1487 std::vector<const Channel *> result;
1488 result.reserve(remapped_channels_.size());
1489 for (auto &pair : remapped_channels_) {
1490 const Channel *const logged_channel =
1491 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1492
1493 auto channel_iterator = std::lower_bound(
1494 remapped_configuration_->channels()->cbegin(),
1495 remapped_configuration_->channels()->cend(),
1496 std::make_pair(std::string_view(pair.second.remapped_name),
1497 logged_channel->type()->string_view()),
1498 CompareChannels);
1499
1500 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1501 CHECK(EqualsChannels(
1502 *channel_iterator,
1503 std::make_pair(std::string_view(pair.second.remapped_name),
1504 logged_channel->type()->string_view())));
1505 result.push_back(*channel_iterator);
1506 }
1507 return result;
1508}
1509
Austin Schuh6f3babe2020-01-26 20:34:50 -08001510const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001511 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001512 const Channel *channel) {
1513 std::string_view channel_name = channel->name()->string_view();
1514 std::string_view channel_type = channel->type()->string_view();
1515 const int channel_index =
1516 configuration::ChannelIndex(logged_configuration(), channel);
1517 // If the channel is remapped, find the correct channel name to use.
1518 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001519 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001520 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001521 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001522 }
1523
Austin Schuhee711052020-08-24 16:06:09 -07001524 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001525 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001526 configuration(), channel_name, channel_type,
1527 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001528
1529 CHECK(remapped_channel != nullptr)
1530 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1531 << channel_type << "\"} because it is not in the provided configuration.";
1532
1533 return remapped_channel;
1534}
1535
James Kuszmaul09632422022-05-25 15:56:19 -07001536LogReader::State::State(
1537 std::unique_ptr<TimestampMapper> timestamp_mapper,
1538 message_bridge::MultiNodeNoncausalOffsetEstimator *multinode_filters,
1539 const Node *node)
1540 : timestamp_mapper_(std::move(timestamp_mapper)),
1541 node_(node),
1542 multinode_filters_(multinode_filters) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001543
1544void LogReader::State::AddPeer(State *peer) {
1545 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1546 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1547 }
1548}
Austin Schuh858c9f32020-08-31 16:56:12 -07001549
Austin Schuh58646e22021-08-23 23:51:46 -07001550void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001551 NodeEventLoopFactory *node_event_loop_factory,
1552 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001553 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001554 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001555}
1556
1557void LogReader::State::SetChannelCount(size_t count) {
1558 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001559 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001560 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001561 channel_source_state_.resize(count);
1562 factory_channel_index_.resize(count);
1563 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001564}
1565
Austin Schuh58646e22021-08-23 23:51:46 -07001566void LogReader::State::SetRemoteTimestampSender(
1567 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1568 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1569}
1570
Austin Schuh858c9f32020-08-31 16:56:12 -07001571void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001572 size_t logged_channel_index, size_t factory_channel_index,
1573 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001574 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1575 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001576 channels_[logged_channel_index] = std::move(sender);
1577 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001578 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001579
Austin Schuh58646e22021-08-23 23:51:46 -07001580 if (is_forwarded) {
1581 queue_index_map_[logged_channel_index] =
1582 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001583 }
1584
1585 factory_channel_index_[logged_channel_index] = factory_channel_index;
1586}
1587
Austin Schuh287d43d2020-12-04 20:19:33 -08001588bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1589 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001590 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001591 uint32_t remote_queue_index = 0xffffffff;
1592
Austin Schuh287d43d2020-12-04 20:19:33 -08001593 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001594 State *source_state =
1595 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001596 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001597 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001598 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001599
Austin Schuh9942bae2021-01-07 22:06:44 -08001600 struct SentTimestamp {
1601 monotonic_clock::time_point monotonic_event_time;
1602 uint32_t queue_index;
1603 } search;
1604
Austin Schuh58646e22021-08-23 23:51:46 -07001605 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1606 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001607 search.monotonic_event_time =
1608 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001609 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001610
1611 // Find the sent time if available.
1612 auto element = std::lower_bound(
1613 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001614 [](ContiguousSentTimestamp a, SentTimestamp b) {
1615 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001616 return true;
1617 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001618 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001619 return false;
1620 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001621
1622 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001623 return true;
1624 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001625 if (a.starting_queue_index >= b.queue_index) {
1626 return false;
1627 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001628
Austin Schuh9942bae2021-01-07 22:06:44 -08001629 // If it isn't clearly below or above, it is below. Since we return
1630 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001631 return false;
1632 });
1633
1634 // TODO(austin): Be a bit more principled here, but we will want to do that
1635 // after the logger rewrite. We hit this when one node finishes, but the
1636 // other node isn't done yet. So there is no send time, but there is a
1637 // receive time.
1638 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001639 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1640 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001641
1642 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001643 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001644 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001645 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001646 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001647 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001648 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001649 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001650
Austin Schuh58646e22021-08-23 23:51:46 -07001651 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001652 element->actual_queue_index -
1653 element->starting_queue_index;
1654 } else {
1655 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001656 }
Austin Schuh58646e22021-08-23 23:51:46 -07001657 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1658 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001659 }
1660
James Kuszmaul09632422022-05-25 15:56:19 -07001661 if (event_loop_factory_ != nullptr &&
1662 channel_source_state_[timestamped_message.channel_index] != nullptr &&
1663 multinode_filters_ != nullptr) {
1664 // Sanity check that we are using consistent boot uuids.
1665 State *source_state =
1666 channel_source_state_[timestamped_message.channel_index];
1667 CHECK_EQ(multinode_filters_->boot_uuid(
1668 configuration::GetNodeIndex(event_loop_->configuration(),
1669 source_state->node()),
1670 timestamped_message.monotonic_remote_time.boot),
1671 CHECK_NOTNULL(
1672 CHECK_NOTNULL(
1673 channel_source_state_[timestamped_message.channel_index])
1674 ->event_loop_)
1675 ->boot_uuid());
1676 }
1677
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001678 // Send! Use the replayed queue index here instead of the logged queue index
1679 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001680 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001681 RawSender::SharedSpan(timestamped_message.data,
1682 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001683 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001684 timestamped_message.realtime_remote_time, remote_queue_index,
1685 (channel_source_state_[timestamped_message.channel_index] != nullptr
James Kuszmaul09632422022-05-25 15:56:19 -07001686 ? CHECK_NOTNULL(multinode_filters_)
1687 ->boot_uuid(configuration::GetNodeIndex(
1688 event_loop_->configuration(),
1689 channel_source_state_[timestamped_message
1690 .channel_index]
1691 ->node()),
1692 timestamped_message.monotonic_remote_time.boot)
Austin Schuh8902fa52021-03-14 22:39:24 -07001693 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001694 if (err != RawSender::Error::kOk) return false;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001695
Austin Schuh287d43d2020-12-04 20:19:33 -08001696 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001697 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001698 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1699 // Nothing here, start a range with 0 length.
1700 ContiguousSentTimestamp timestamp;
1701 timestamp.starting_monotonic_event_time =
1702 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001703 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001704 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001705 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001706 timestamp.actual_queue_index = sender->sent_queue_index();
1707 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1708 timestamp);
1709 } else {
1710 // We've got something. See if the next timestamp is still contiguous. If
1711 // so, grow it.
1712 ContiguousSentTimestamp *back =
1713 &queue_index_map_[timestamped_message.channel_index]->back();
1714 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001715 (timestamped_message.queue_index.index -
1716 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001717 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001718 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001719 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001720 } else {
1721 // Otherwise, make a new one.
1722 ContiguousSentTimestamp timestamp;
1723 timestamp.starting_monotonic_event_time =
1724 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001725 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001726 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001727 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001728 timestamp.actual_queue_index = sender->sent_queue_index();
1729 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1730 timestamp);
1731 }
1732 }
1733
1734 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1735 // queue index diverge a couple of elements, which would be a very small
1736 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001737 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1738 nullptr) {
James Kuszmaul09632422022-05-25 15:56:19 -07001739 // TODO(james): Currently, If running replay against a single event loop,
1740 // remote timestamps will not get replayed because this code-path only
1741 // gets triggered on the event loop that receives the forwarded message
1742 // that the timestamps correspond to. This code, as written, also doesn't
1743 // correctly handle a non-zero clock_offset for the *_remote_time fields.
Austin Schuh58646e22021-08-23 23:51:46 -07001744 State *source_state =
1745 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1746
Austin Schuh969cd602021-01-03 00:09:45 -08001747 flatbuffers::FlatBufferBuilder fbb;
1748 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001749 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1750 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001751
Austin Schuh969cd602021-01-03 00:09:45 -08001752 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001753
1754 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001755 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001756
1757 // Swap the remote and sent metrics. They are from the sender's
1758 // perspective, not the receiver's perspective.
1759 message_header_builder.add_monotonic_sent_time(
1760 sender->monotonic_sent_time().time_since_epoch().count());
1761 message_header_builder.add_realtime_sent_time(
1762 sender->realtime_sent_time().time_since_epoch().count());
1763 message_header_builder.add_queue_index(sender->sent_queue_index());
1764
Austin Schuh58646e22021-08-23 23:51:46 -07001765 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1766 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001767 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001768 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1769 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001770 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001771 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001772
1773 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001774 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001775
Austin Schuh969cd602021-01-03 00:09:45 -08001776 fbb.Finish(message_header_builder.Finish());
1777
1778 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1779 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001780 timestamped_message.monotonic_timestamp_time,
1781 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001782 }
1783
1784 return true;
1785}
1786
Austin Schuh969cd602021-01-03 00:09:45 -08001787LogReader::RemoteMessageSender::RemoteMessageSender(
1788 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1789 : event_loop_(event_loop),
1790 sender_(std::move(sender)),
1791 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1792
1793void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1794 if (remote_timestamps_.empty()) {
1795 CHECK_NOTNULL(timer_);
1796 timer_->Disable();
1797 scheduled_time_ = monotonic_clock::min_time;
1798 return;
1799 }
1800
1801 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1802 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001803 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001804 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001805 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1806 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001807 }
1808}
1809
1810void LogReader::RemoteMessageSender::Send(
1811 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001812 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001813 // There are 2 variants of logs.
1814 // 1) Logs without monotonic_timestamp_time
1815 // 2) Logs with monotonic_timestamp_time
1816 //
1817 // As of Jan 2021, we shouldn't have any more logs without
1818 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1819 // the effort of saving.
1820 //
1821 // This gives us 3 cases, 2 of which are undistinguishable.
1822 // 1) Old log without monotonic_timestamp_time.
1823 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1824 // remotely so we actually have monotonic_timestamp_time.
1825 // 3) New log, but the timestamp was logged on the node receiving the message
1826 // so there is no monotonic_timestamp_time.
1827 //
1828 // Our goal when replaying is to accurately reproduce the state of the world
1829 // present when logging. If a timestamp wasn't sent back across the network,
1830 // we shouldn't replay one back across the network.
1831 //
1832 // Given that we don't really care about 1, we can use the presence of the
1833 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1834 // monotonic_timestamp_time, this means the message was logged locally and
1835 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001836 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001837 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001838 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001839
Austin Schuh58646e22021-08-23 23:51:46 -07001840 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
1841
Austin Schuhc41d6a82021-07-16 14:49:23 -07001842 remote_timestamps_.emplace(
1843 std::upper_bound(
1844 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07001845 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07001846 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1847 const Timestamp &timestamp) {
1848 return monotonic_timestamp_time <
1849 timestamp.monotonic_timestamp_time;
1850 }),
Austin Schuh58646e22021-08-23 23:51:46 -07001851 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07001852 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001853}
1854
1855void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001856 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1857 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001858 CHECK(!remote_timestamps_.empty());
1859
1860 // Send out all timestamps at the currently scheduled time.
1861 while (remote_timestamps_.front().monotonic_timestamp_time ==
1862 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07001863 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
1864 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08001865 remote_timestamps_.pop_front();
1866 if (remote_timestamps_.empty()) {
1867 break;
1868 }
1869 }
1870 scheduled_time_ = monotonic_clock::min_time;
1871
1872 ScheduleTimestamp();
1873}
1874
1875LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001876 const Channel *channel, const Connection *connection) {
1877 message_bridge::ChannelTimestampFinder finder(event_loop_);
1878 // Look at any pre-created channel/connection pairs.
1879 {
1880 auto it =
1881 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1882 if (it != channel_timestamp_loggers_.end()) {
1883 return it->second.get();
1884 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001885 }
1886
Austin Schuh61e973f2021-02-21 21:43:56 -08001887 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1888 // to.
1889 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1890
1891 {
1892 // See if that has been created before. If so, cache it in
1893 // channel_timestamp_loggers_ and return.
1894 auto it = timestamp_loggers_.find(timestamp_channel);
1895 if (it != timestamp_loggers_.end()) {
1896 CHECK(channel_timestamp_loggers_
1897 .try_emplace(std::make_pair(channel, connection), it->second)
1898 .second);
1899 return it->second.get();
1900 }
1901 }
1902
1903 // Otherwise, make a sender, save it, and cache it.
1904 auto result = channel_timestamp_loggers_.try_emplace(
1905 std::make_pair(channel, connection),
1906 std::make_shared<RemoteMessageSender>(
1907 event_loop()->MakeSender<RemoteMessage>(
1908 timestamp_channel->name()->string_view()),
1909 event_loop()));
1910
1911 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1912 .second);
1913 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001914}
1915
Austin Schuhdda74ec2021-01-03 19:30:37 -08001916TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001917 CHECK(timestamp_mapper_ != nullptr);
1918 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1919 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001920
Austin Schuhe639ea12021-01-25 13:00:22 -08001921 TimestampedMessage result = std::move(*result_ptr);
1922
Austin Schuh2f8fd752020-09-01 22:38:28 -07001923 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001924 << result.monotonic_event_time;
1925 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001926 SeedSortedMessages();
1927
Austin Schuh58646e22021-08-23 23:51:46 -07001928 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001929
Austin Schuh5ee56872021-01-30 16:53:34 -08001930 VLOG(1) << "Popped " << result
1931 << configuration::CleanedChannelToString(
1932 event_loop_->configuration()->channels()->Get(
1933 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001934 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001935}
1936
Austin Schuhe33c08d2022-02-03 18:15:21 -08001937BootTimestamp LogReader::State::OldestMessageTime() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001938 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001939 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08001940 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001941 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1942 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001943 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08001944 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08001945 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001946 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001947
1948 if (result_ptr->monotonic_event_time.boot == boot_count()) {
1949 ObserveNextMessage(result_ptr->monotonic_event_time.time,
1950 result_ptr->realtime_event_time);
1951 }
1952
Austin Schuh58646e22021-08-23 23:51:46 -07001953 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001954}
1955
1956void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001957 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001958
Austin Schuhe639ea12021-01-25 13:00:22 -08001959 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1960 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001961}
1962
1963void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07001964 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001965 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001966 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001967 for (size_t i = 0; i < channels_.size(); ++i) {
1968 channels_[i].reset();
1969 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08001970 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08001971 channel_timestamp_loggers_.clear();
1972 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001973 event_loop_unique_ptr_.reset();
1974 event_loop_ = nullptr;
1975 timer_handler_ = nullptr;
1976 node_event_loop_factory_ = nullptr;
1977}
1978
Austin Schuhe33c08d2022-02-03 18:15:21 -08001979void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
1980 if (start_time != realtime_clock::min_time) {
1981 start_event_notifier_ = std::make_unique<EventNotifier>(
1982 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
1983 }
1984}
1985
1986void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
1987 if (end_time != realtime_clock::max_time) {
1988 end_event_notifier_ = std::make_unique<EventNotifier>(
1989 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
1990 }
1991}
1992
1993void LogReader::State::ObserveNextMessage(
1994 monotonic_clock::time_point monotonic_event,
1995 realtime_clock::time_point realtime_event) {
1996 if (start_event_notifier_) {
1997 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
1998 }
1999 if (end_event_notifier_) {
2000 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
2001 }
2002}
2003
2004void LogReader::State::ClearTimeFlags() {
2005 start_event_notifier_.reset();
2006 end_event_notifier_.reset();
2007}
2008
2009void LogReader::State::NotifyLogfileStart() {
2010 if (start_event_notifier_) {
2011 if (start_event_notifier_->realtime_event_time() >
2012 realtime_start_time(boot_count())) {
2013 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
2014 << " > " << realtime_start_time(boot_count());
2015 return;
2016 }
2017 }
2018 if (found_last_message_) {
2019 VLOG(1) << "Last message already found, bailing";
2020 return;
2021 }
2022 RunOnStart();
2023}
2024
2025void LogReader::State::NotifyFlagStart() {
2026 if (start_event_notifier_->realtime_event_time() >=
2027 realtime_start_time(boot_count())) {
2028 RunOnStart();
2029 }
2030}
2031
2032void LogReader::State::NotifyLogfileEnd() {
2033 if (found_last_message_) {
2034 return;
2035 }
2036
2037 if (!stopped_ && started_) {
2038 RunOnEnd();
2039 }
2040}
2041
2042void LogReader::State::NotifyFlagEnd() {
2043 if (!stopped_ && started_) {
2044 RunOnEnd();
2045 SetFoundLastMessage(true);
2046 }
2047}
2048
James Kuszmaul09632422022-05-25 15:56:19 -07002049void LogReader::State::SetClockOffset() {
2050 if (node_event_loop_factory_ == nullptr) {
2051 // If not running with simulated event loop, set the monotonic clock
2052 // offset.
2053 clock_offset_ = event_loop()->monotonic_now() - monotonic_start_time(0);
2054
2055 if (start_event_notifier_) {
2056 start_event_notifier_->SetClockOffset(clock_offset_);
2057 }
2058 if (end_event_notifier_) {
2059 end_event_notifier_->SetClockOffset(clock_offset_);
2060 }
2061 }
2062}
2063
Austin Schuhe309d2a2019-11-29 13:25:21 -08002064} // namespace logger
2065} // namespace aos