blob: 4e89a0e6e770eae7db47e2c842d4470ea99ebf2f [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"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080018#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080019#include "aos/network/remote_message_generated.h"
20#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080021#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080022#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080023#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070024#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070025#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080026#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080027#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028
Austin Schuh15649d62019-12-28 16:36:38 -080029DEFINE_bool(skip_missing_forwarding_entries, false,
30 "If true, drop any forwarding entries with missing data. If "
31 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080032
Austin Schuh0ca1fd32020-12-18 22:53:05 -080033DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080034
Austin Schuh2f8fd752020-09-01 22:38:28 -070035DEFINE_bool(skip_order_validation, false,
36 "If true, ignore any out of orderness in replay");
37
Austin Schuhf0688662020-12-19 15:37:45 -080038DEFINE_double(
39 time_estimation_buffer_seconds, 2.0,
40 "The time to buffer ahead in the log file to accurately reconstruct time.");
41
Austin Schuhe33c08d2022-02-03 18:15:21 -080042DEFINE_string(
43 start_time, "",
44 "If set, start at this point in time in the log on the realtime clock.");
45DEFINE_string(
46 end_time, "",
47 "If set, end at this point in time in the log on the realtime clock.");
48
Austin Schuhe309d2a2019-11-29 13:25:21 -080049namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070050namespace configuration {
51// We don't really want to expose this publicly, but log reader doesn't really
52// want to re-implement it.
53void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
54 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070055} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080056namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070057namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080058
Austin Schuh1c227352021-09-17 12:53:54 -070059bool CompareChannels(const Channel *c,
60 ::std::pair<std::string_view, std::string_view> p) {
61 int name_compare = c->name()->string_view().compare(p.first);
62 if (name_compare == 0) {
63 return c->type()->string_view() < p.second;
64 } else if (name_compare < 0) {
65 return true;
66 } else {
67 return false;
68 }
69}
70
71bool EqualsChannels(const Channel *c,
72 ::std::pair<std::string_view, std::string_view> p) {
73 return c->name()->string_view() == p.first &&
74 c->type()->string_view() == p.second;
75}
76
Austin Schuh0de30f32020-12-06 12:44:28 -080077// Copies the channel, removing the schema as we go. If new_name is provided,
78// it is used instead of the name inside the channel. If new_type is provided,
79// it is used instead of the type in the channel.
80flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
81 std::string_view new_name,
82 std::string_view new_type,
83 flatbuffers::FlatBufferBuilder *fbb) {
84 flatbuffers::Offset<flatbuffers::String> name_offset =
85 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
86 : new_name);
87 flatbuffers::Offset<flatbuffers::String> type_offset =
88 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
89 flatbuffers::Offset<flatbuffers::String> source_node_offset =
90 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
91 : 0;
92
93 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
94 destination_nodes_offset =
95 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
96
97 flatbuffers::Offset<
98 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
99 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
100
101 Channel::Builder channel_builder(*fbb);
102 channel_builder.add_name(name_offset);
103 channel_builder.add_type(type_offset);
104 if (c->has_frequency()) {
105 channel_builder.add_frequency(c->frequency());
106 }
107 if (c->has_max_size()) {
108 channel_builder.add_max_size(c->max_size());
109 }
110 if (c->has_num_senders()) {
111 channel_builder.add_num_senders(c->num_senders());
112 }
113 if (c->has_num_watchers()) {
114 channel_builder.add_num_watchers(c->num_watchers());
115 }
116 if (!source_node_offset.IsNull()) {
117 channel_builder.add_source_node(source_node_offset);
118 }
119 if (!destination_nodes_offset.IsNull()) {
120 channel_builder.add_destination_nodes(destination_nodes_offset);
121 }
122 if (c->has_logger()) {
123 channel_builder.add_logger(c->logger());
124 }
125 if (!logger_nodes_offset.IsNull()) {
126 channel_builder.add_logger_nodes(logger_nodes_offset);
127 }
128 if (c->has_read_method()) {
129 channel_builder.add_read_method(c->read_method());
130 }
131 if (c->has_num_readers()) {
132 channel_builder.add_num_readers(c->num_readers());
133 }
134 return channel_builder.Finish();
135}
136
Austin Schuhe309d2a2019-11-29 13:25:21 -0800137namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800138using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700139} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800140
Austin Schuhe33c08d2022-02-03 18:15:21 -0800141// Class to manage triggering events on the RT clock while replaying logs. Since
142// the RT clock can only change when we get a message, we only need to update
143// our timers when new messages are read.
144class EventNotifier {
145 public:
146 EventNotifier(EventLoop *event_loop, std::function<void()> fn,
147 std::string_view name,
148 realtime_clock::time_point realtime_event_time)
149 : event_loop_(event_loop),
150 fn_(std::move(fn)),
151 realtime_event_time_(realtime_event_time) {
152 CHECK(event_loop_);
153 event_timer_ = event_loop->AddTimer([this]() { HandleTime(); });
154
155 if (event_loop_->node() != nullptr) {
156 event_timer_->set_name(
157 absl::StrCat(event_loop_->node()->name()->string_view(), "_", name));
158 } else {
159 event_timer_->set_name(name);
160 }
161 }
162
163 ~EventNotifier() { event_timer_->Disable(); }
164
165 // Returns the event trigger time.
166 realtime_clock::time_point realtime_event_time() const {
167 return realtime_event_time_;
168 }
169
170 // Observes the next message and potentially calls the callback or updates the
171 // timer.
172 void ObserveNextMessage(monotonic_clock::time_point monotonic_message_time,
173 realtime_clock::time_point realtime_message_time) {
174 if (realtime_message_time < realtime_event_time_) {
175 return;
176 }
177 if (called_) {
178 return;
179 }
180
181 // Move the callback wakeup time to the correct time (or make it now if
182 // there's a gap in time) now that we know it is before the next
183 // message.
184 const monotonic_clock::time_point candidate_monotonic =
185 (realtime_event_time_ - realtime_message_time) + monotonic_message_time;
186 const monotonic_clock::time_point monotonic_now =
187 event_loop_->monotonic_now();
188 if (candidate_monotonic < monotonic_now) {
189 // Whops, time went backwards. Just do it now.
190 HandleTime();
191 } else {
192 event_timer_->Setup(candidate_monotonic);
193 }
194 }
195
196 private:
197 void HandleTime() {
198 if (!called_) {
199 called_ = true;
200 fn_();
201 }
202 }
203
204 EventLoop *event_loop_ = nullptr;
205 TimerHandler *event_timer_ = nullptr;
206 std::function<void()> fn_;
207
208 const realtime_clock::time_point realtime_event_time_ =
209 realtime_clock::min_time;
210
211 bool called_ = false;
212};
213
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800214LogReader::LogReader(std::string_view filename,
215 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800216 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800217
Austin Schuh287d43d2020-12-04 20:19:33 -0800218LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800219 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800220 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800221 replay_configuration_(replay_configuration) {
Austin Schuhe33c08d2022-02-03 18:15:21 -0800222 SetStartTime(FLAGS_start_time);
223 SetEndTime(FLAGS_end_time);
224
Austin Schuh0ca51f32020-12-25 21:51:45 -0800225 CHECK_GT(log_files_.size(), 0u);
226 {
227 // Validate that we have the same config everwhere. This will be true if
228 // all the parts were sorted together and the configs match.
229 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800230 for (const LogFile &log_file : log_files_) {
231 if (log_file.config.get() == nullptr) {
232 LOG(FATAL) << "Couldn't find a config in " << log_file;
233 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800234 if (config == nullptr) {
235 config = log_file.config.get();
236 } else {
237 CHECK_EQ(config, log_file.config.get());
238 }
239 }
240 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800241
Austin Schuh6331ef92020-01-07 18:28:09 -0800242 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800243
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700244 // Remap all existing remote timestamp channels. They will be recreated, and
245 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700246 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800247 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
248 "log_reader", node);
249
250 absl::btree_set<std::string_view> remote_nodes;
251
252 for (const Channel *channel : *logged_configuration()->channels()) {
253 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
254 continue;
255 }
256 if (!channel->has_destination_nodes()) {
257 continue;
258 }
259 for (const Connection *connection : *channel->destination_nodes()) {
260 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
261 node)) {
262 // Start by seeing if the split timestamp channels are being used for
263 // this message. If so, remap them.
264 const Channel *timestamp_channel = configuration::GetChannel(
265 logged_configuration(),
266 finder.SplitChannelName(channel, connection),
267 RemoteMessage::GetFullyQualifiedName(), "", node, true);
268
269 if (timestamp_channel != nullptr) {
270 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
271 RemapLoggedChannel<RemoteMessage>(
272 timestamp_channel->name()->string_view(), node);
273 }
274 continue;
275 }
276
277 // Otherwise collect this one up as a node to look for a combined
278 // channel from. It is more efficient to compare nodes than channels.
279 remote_nodes.insert(connection->name()->string_view());
280 }
281 }
282 }
283
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700284 std::vector<const Node *> timestamp_logger_nodes =
285 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800286 for (const std::string_view remote_node : remote_nodes) {
287 const std::string channel = finder.CombinedChannelName(remote_node);
288
Austin Schuh0de30f32020-12-06 12:44:28 -0800289 // See if the log file is an old log with MessageHeader channels in it, or
290 // a newer log with RemoteMessage. If we find an older log, rename the
291 // type too along with the name.
292 if (HasChannel<MessageHeader>(channel, node)) {
293 CHECK(!HasChannel<RemoteMessage>(channel, node))
294 << ": Can't have both a MessageHeader and RemoteMessage remote "
295 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800296 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
297 // careful about updating the config, but there are fewer and fewer logs
298 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800299 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
300 "aos.message_bridge.RemoteMessage");
301 } else {
302 CHECK(HasChannel<RemoteMessage>(channel, node))
303 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
304 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
305 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800306 // Only bother to remap if there's something on the channel. We can
307 // tell if the channel was marked NOT_LOGGED or not. This makes the
308 // config not change un-necesarily when we replay a log with NOT_LOGGED
309 // messages.
310 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
311 RemapLoggedChannel<RemoteMessage>(channel, node);
312 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800313 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700314 }
315 }
316
Austin Schuh6aa77be2020-02-22 21:06:40 -0800317 if (replay_configuration) {
318 CHECK_EQ(configuration::MultiNode(configuration()),
319 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 << ": Log file and replay config need to both be multi or single "
321 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800322 }
323
Austin Schuh6f3babe2020-01-26 20:34:50 -0800324 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800325 states_.emplace_back(std::make_unique<State>(
Austin Schuh58646e22021-08-23 23:51:46 -0700326 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, "")),
327 nullptr));
Austin Schuh8bd96322020-02-13 21:18:22 -0800328 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800329 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700330 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800331 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700332 << ": Log file and replay config need to have matching nodes "
333 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700334 for (const Node *node : *logged_configuration()->nodes()) {
335 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700336 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
337 << " in logged config that is not present in the replay "
338 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700339 }
340 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800341 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800342 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800343 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800344}
345
Austin Schuh6aa77be2020-02-22 21:06:40 -0800346LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700347 if (event_loop_factory_unique_ptr_) {
348 Deregister();
349 } else if (event_loop_factory_ != nullptr) {
350 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
351 "is destroyed";
352 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700353 // Zero out some buffers. It's easy to do use-after-frees on these, so make
354 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700355 if (remapped_configuration_buffer_) {
356 remapped_configuration_buffer_->Wipe();
357 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800358}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800359
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800360const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800361 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800362}
363
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800364const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800365 return remapped_configuration_;
366}
367
Austin Schuh07676622021-01-21 18:59:17 -0800368std::vector<const Node *> LogReader::LoggedNodes() const {
369 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800370}
Austin Schuh15649d62019-12-28 16:36:38 -0800371
Austin Schuh11d43732020-09-21 17:28:30 -0700372monotonic_clock::time_point LogReader::monotonic_start_time(
373 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800374 State *state =
375 states_[configuration::GetNodeIndex(configuration(), node)].get();
376 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
377
Austin Schuhf665eb42022-02-03 18:26:25 -0800378 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800379}
380
Austin Schuh11d43732020-09-21 17:28:30 -0700381realtime_clock::time_point LogReader::realtime_start_time(
382 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800383 State *state =
384 states_[configuration::GetNodeIndex(configuration(), node)].get();
385 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
386
Austin Schuhf665eb42022-02-03 18:26:25 -0800387 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800388}
389
Austin Schuh58646e22021-08-23 23:51:46 -0700390void LogReader::OnStart(std::function<void()> fn) {
391 CHECK(!configuration::MultiNode(configuration()));
392 OnStart(nullptr, std::move(fn));
393}
394
395void LogReader::OnStart(const Node *node, std::function<void()> fn) {
396 const int node_index = configuration::GetNodeIndex(configuration(), node);
397 CHECK_GE(node_index, 0);
398 CHECK_LT(node_index, static_cast<int>(states_.size()));
399 State *state = states_[node_index].get();
400 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
401
402 state->OnStart(std::move(fn));
403}
404
405void LogReader::State::OnStart(std::function<void()> fn) {
406 on_starts_.emplace_back(std::move(fn));
407}
408
409void LogReader::State::RunOnStart() {
410 SetRealtimeOffset(monotonic_start_time(boot_count()),
411 realtime_start_time(boot_count()));
412
413 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
414 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800415 auto fn = [this]() {
416 for (size_t i = 0; i < on_starts_.size(); ++i) {
417 on_starts_[i]();
418 }
419 };
420 if (event_loop_factory_) {
421 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
422 } else {
423 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700424 }
425 stopped_ = false;
426 started_ = true;
427}
428
429void LogReader::OnEnd(std::function<void()> fn) {
430 CHECK(!configuration::MultiNode(configuration()));
431 OnEnd(nullptr, std::move(fn));
432}
433
434void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
435 const int node_index = configuration::GetNodeIndex(configuration(), node);
436 CHECK_GE(node_index, 0);
437 CHECK_LT(node_index, static_cast<int>(states_.size()));
438 State *state = states_[node_index].get();
439 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
440
441 state->OnEnd(std::move(fn));
442}
443
444void LogReader::State::OnEnd(std::function<void()> fn) {
445 on_ends_.emplace_back(std::move(fn));
446}
447
448void LogReader::State::RunOnEnd() {
449 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
450 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800451 auto fn = [this]() {
452 for (size_t i = 0; i < on_ends_.size(); ++i) {
453 on_ends_[i]();
454 }
455 };
456 if (event_loop_factory_) {
457 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
458 } else {
459 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700460 }
461
462 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800463 started_ = true;
Austin Schuh58646e22021-08-23 23:51:46 -0700464}
465
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800466void LogReader::Register() {
467 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800468 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800469 Register(event_loop_factory_unique_ptr_.get());
470}
471
Austin Schuh58646e22021-08-23 23:51:46 -0700472void LogReader::RegisterWithoutStarting(
473 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800474 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700475 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800476 filters_ =
477 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800478 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700479 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800480 chrono::duration_cast<chrono::nanoseconds>(
481 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800482
Austin Schuhe639ea12021-01-25 13:00:22 -0800483 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700484 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800485 const size_t node_index =
486 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800487 std::vector<LogParts> filtered_parts = FilterPartsForNode(
488 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800489
Austin Schuh287d43d2020-12-04 20:19:33 -0800490 states_[node_index] = std::make_unique<State>(
491 filtered_parts.size() == 0u
492 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700493 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
494 node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800495 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700496 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800497 event_loop_factory_->GetNodeEventLoopFactory(node),
498 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700499
500 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800501 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800502 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800503 filters_->SetTimestampMappers(std::move(timestamp_mappers));
504
505 // Note: this needs to be set before any times are pulled, or we won't observe
506 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800507 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700508
Austin Schuh287d43d2020-12-04 20:19:33 -0800509 for (const Node *node : configuration::GetNodes(configuration())) {
510 const size_t node_index =
511 configuration::GetNodeIndex(configuration(), node);
512 State *state = states_[node_index].get();
513 for (const Node *other_node : configuration::GetNodes(configuration())) {
514 const size_t other_node_index =
515 configuration::GetNodeIndex(configuration(), other_node);
516 State *other_state = states_[other_node_index].get();
517 if (other_state != state) {
518 state->AddPeer(other_state);
519 }
520 }
521 }
522
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700523 // Register after making all the State objects so we can build references
524 // between them.
525 for (const Node *node : configuration::GetNodes(configuration())) {
526 const size_t node_index =
527 configuration::GetNodeIndex(configuration(), node);
528 State *state = states_[node_index].get();
529
Austin Schuh58646e22021-08-23 23:51:46 -0700530 // If we didn't find any log files with data in them, we won't ever get a
531 // callback or be live. So skip the rest of the setup.
532 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
533 continue;
534 }
535 ++live_nodes_;
536
537 NodeEventLoopFactory *node_factory =
538 event_loop_factory_->GetNodeEventLoopFactory(node);
539 node_factory->OnStartup([this, state, node]() {
540 RegisterDuringStartup(state->MakeEventLoop(), node);
541 });
542 node_factory->OnShutdown([this, state, node]() {
543 RegisterDuringStartup(nullptr, node);
544 state->DestroyEventLoop();
545 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700546 }
547
James Kuszmaul46d82582020-05-09 19:50:09 -0700548 if (live_nodes_ == 0) {
549 LOG(FATAL)
550 << "Don't have logs from any of the nodes in the replay config--are "
551 "you sure that the replay config matches the original config?";
552 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800553
Austin Schuh87dd3832021-01-01 23:07:31 -0800554 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800555
Austin Schuh858c9f32020-08-31 16:56:12 -0700556 for (std::unique_ptr<State> &state : states_) {
557 state->SeedSortedMessages();
558 }
559
Austin Schuh6f3babe2020-01-26 20:34:50 -0800560 // Forwarding is tracked per channel. If it is enabled, we want to turn it
561 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700562 // nodes, and also replayed on the other nodes. This may not satisfy all
563 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800564 if (configuration::MultiNode(event_loop_factory_->configuration())) {
565 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
566 const Channel *channel = logged_configuration()->channels()->Get(i);
567 const Node *node = configuration::GetNode(
568 configuration(), channel->source_node()->string_view());
569
Austin Schuh8bd96322020-02-13 21:18:22 -0800570 State *state =
571 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800572
573 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700574 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800575
576 event_loop_factory_->DisableForwarding(remapped_channel);
577 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700578
579 // If we are replaying a log, we don't want a bunch of redundant messages
580 // from both the real message bridge and simulated message bridge.
581 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800582 }
Austin Schuh891214d2021-11-11 20:35:02 -0800583
584 // Write pseudo start times out to file now that we are all setup.
585 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700586}
587
588void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
589 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800590 StartAfterRegister(event_loop_factory);
591}
592
593void LogReader::StartAfterRegister(
594 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700595 // We want to start the log file at the last start time of the log files
596 // from all the nodes. Compute how long each node's simulation needs to run
597 // to move time to this point.
598 distributed_clock::time_point start_time = distributed_clock::min_time;
599
600 // TODO(austin): We want an "OnStart" callback for each node rather than
601 // running until the last node.
602
603 for (std::unique_ptr<State> &state : states_) {
604 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
605 << " for node " << MaybeNodeName(state->node()) << "now "
606 << state->monotonic_now();
607 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
608 continue;
609 }
610 // And start computing the start time on the distributed clock now that
611 // that works.
612 start_time = std::max(
613 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
614 }
615
616 // TODO(austin): If a node doesn't have a start time, we might not queue
617 // enough. If this happens, we'll explode with a frozen error eventually.
618
619 CHECK_GE(start_time, distributed_clock::epoch())
620 << ": Hmm, we have a node starting before the start of time. Offset "
621 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800622
Austin Schuhcde938c2020-02-02 17:30:07 -0800623 // While we are starting the system up, we might be relying on matching data
624 // to timestamps on log files where the timestamp log file starts before the
625 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800626 {
627 const bool prior_ignore_missing_data = ignore_missing_data_;
628 ignore_missing_data_ = true;
629 VLOG(1) << "Running until " << start_time << " in Register";
630 event_loop_factory_->RunFor(start_time.time_since_epoch());
631 VLOG(1) << "At start time";
632 // Now that we are running for real, missing data means that the log file is
633 // corrupted or went wrong.
634 ignore_missing_data_ = prior_ignore_missing_data;
635 }
Austin Schuh92547522019-12-28 14:33:43 -0800636
Austin Schuh8bd96322020-02-13 21:18:22 -0800637 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700638 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700639 if (state->realtime_start_time(0) != realtime_clock::min_time) {
640 state->SetRealtimeOffset(state->monotonic_start_time(0),
641 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700642 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700643 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
644 << " for node " << MaybeNodeName(state->event_loop()->node())
645 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700646 }
647
648 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800649 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800650 }
651}
652
Austin Schuh2f8fd752020-09-01 22:38:28 -0700653message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800654 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800655 if (filters_) {
656 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800657 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800658 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800659}
660
Austin Schuhe309d2a2019-11-29 13:25:21 -0800661void LogReader::Register(EventLoop *event_loop) {
Austin Schuh58646e22021-08-23 23:51:46 -0700662 Register(event_loop, event_loop->node());
663}
664
665void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800666 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700667 states_[configuration::GetNodeIndex(configuration(), node)].get();
668
669 // If we didn't find any log files with data in them, we won't ever get a
670 // callback or be live. So skip the rest of the setup.
671 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
672 return;
673 }
674 ++live_nodes_;
675
676 if (event_loop_factory_ != nullptr) {
677 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
678 [this, event_loop, node]() {
679 RegisterDuringStartup(event_loop, node);
680 });
681 } else {
682 RegisterDuringStartup(event_loop, node);
683 }
684}
685
686void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
687 if (event_loop) {
688 CHECK(event_loop->configuration() == configuration());
689 }
690
691 State *state =
692 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800693
Austin Schuhe33c08d2022-02-03 18:15:21 -0800694 if (!event_loop) {
695 state->ClearTimeFlags();
696 }
697
Austin Schuh858c9f32020-08-31 16:56:12 -0700698 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800699
Tyler Chatow67ddb032020-01-12 14:30:04 -0800700 // We don't run timing reports when trying to print out logged data, because
701 // otherwise we would end up printing out the timing reports themselves...
702 // This is only really relevant when we are replaying into a simulation.
Austin Schuh58646e22021-08-23 23:51:46 -0700703 if (event_loop) {
704 event_loop->SkipTimingReport();
705 event_loop->SkipAosLog();
706 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800707
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700708 for (size_t logged_channel_index = 0;
709 logged_channel_index < logged_configuration()->channels()->size();
710 ++logged_channel_index) {
711 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700712 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700713 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800714
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700715 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh532656d2021-01-11 10:17:18 -0800716
Austin Schuh2f8fd752020-09-01 22:38:28 -0700717 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700718
719 State *source_state = nullptr;
Austin Schuh58646e22021-08-23 23:51:46 -0700720 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
721 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700722 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700723 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800724
Austin Schuh58646e22021-08-23 23:51:46 -0700725 // We've got a message which is being forwarded to this node.
726 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700727
728 source_state =
729 states_[configuration::GetNodeIndex(configuration(), source_node)]
730 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800731 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700732
Austin Schuh58646e22021-08-23 23:51:46 -0700733 // We are the source, and it is forwarded.
734 const bool is_forwarded =
735 configuration::ChannelIsSendableOnNode(channel, node) &&
736 configuration::ConnectionCount(channel);
737
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700738 state->SetChannel(
739 logged_channel_index,
740 configuration::ChannelIndex(configuration(), channel),
741 event_loop && logged ? event_loop->MakeRawSender(channel) : nullptr,
742 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700743
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700744 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700745 const Node *source_node = configuration::GetNode(
746 configuration(), channel->source_node()->string_view());
747
748 for (const Connection *connection : *channel->destination_nodes()) {
749 const bool delivery_time_is_logged =
750 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
751 source_node);
752
753 if (delivery_time_is_logged) {
754 State *destination_state =
755 states_[configuration::GetNodeIndex(
756 configuration(), connection->name()->string_view())]
757 .get();
758 destination_state->SetRemoteTimestampSender(
759 logged_channel_index,
760 event_loop ? state->RemoteTimestampSender(channel, connection)
761 : nullptr);
762 }
763 }
764 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800765 }
766
Austin Schuh58646e22021-08-23 23:51:46 -0700767 if (!event_loop) {
768 state->ClearRemoteTimestampSenders();
769 state->set_timer_handler(nullptr);
770 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800771 return;
772 }
773
Austin Schuh858c9f32020-08-31 16:56:12 -0700774 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700775 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
776 << "at " << state->event_loop()->context().monotonic_event_time
777 << " now " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700778 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800779 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700780 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800781 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800782 event_loop_factory_->Exit();
783 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800784 return;
785 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700786
Austin Schuhdda74ec2021-01-03 19:30:37 -0800787 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700788
789 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
790 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800791
Austin Schuhe309d2a2019-11-29 13:25:21 -0800792 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700793 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700794 if (!FLAGS_skip_order_validation) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700795 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700796 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
797 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800798 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700799 << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700800 } else if (BootTimestamp{.boot = state->boot_count(),
801 .time = monotonic_now} !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700802 timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700803 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800804 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700805 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800806 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700807 << "): " << FlatbufferToJson(state->event_loop()->node())
808 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800809 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700810 << state->DebugString();
811 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800812
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700813 if (timestamped_message.monotonic_event_time.time >
814 state->monotonic_start_time(
815 timestamped_message.monotonic_event_time.boot) ||
Austin Schuh15649d62019-12-28 16:36:38 -0800816 event_loop_factory_ != nullptr) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800817 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800818 if (timestamped_message.monotonic_remote_time !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700819 BootTimestamp::min_time()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800820 // Confirm that the message was sent on the sending node before the
821 // destination node (this node). As a proxy, do this by making sure
822 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800823 //
824 // TODO(austin): <= means that the cause message (which we know) could
825 // happen after the effect even though we know they are at the same
826 // time. I doubt anyone will notice for a bit, but we should really
827 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -0700828 BootTimestamp monotonic_remote_now =
829 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700830 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -0700831 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -0800832 monotonic_remote_now.boot)
833 << state->event_loop()->node()->name()->string_view() << " to "
834 << state->remote_node(timestamped_message.channel_index)
835 ->name()
836 ->string_view()
837 << " while trying to send a message on "
838 << configuration::CleanedChannelToString(
839 logged_configuration()->channels()->Get(
840 timestamped_message.channel_index))
841 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700842 CHECK_LE(timestamped_message.monotonic_remote_time,
843 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700844 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800845 << state->remote_node(timestamped_message.channel_index)
846 ->name()
847 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800848 << " while trying to send a message on "
849 << configuration::CleanedChannelToString(
850 logged_configuration()->channels()->Get(
851 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700852 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700853 } else if (monotonic_remote_now.boot !=
854 timestamped_message.monotonic_remote_time.boot) {
855 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
856 << " vs "
857 << timestamped_message.monotonic_remote_time.boot;
858 } else if (timestamped_message.monotonic_remote_time >
859 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700860 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800861 << "Check failed: timestamped_message.monotonic_remote_time < "
862 "state->monotonic_remote_now(timestamped_message.channel_"
863 "index) ("
864 << timestamped_message.monotonic_remote_time << " vs. "
865 << state->monotonic_remote_now(
866 timestamped_message.channel_index)
867 << ") " << state->event_loop()->node()->name()->string_view()
868 << " to "
869 << state->remote_node(timestamped_message.channel_index)
870 ->name()
871 ->string_view()
872 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700873 << " ("
874 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700875 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700876 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800877 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700878 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800879 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700880 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700881 << ") " << state->DebugString();
882 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800883 }
884
Austin Schuh15649d62019-12-28 16:36:38 -0800885 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700886 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800887 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800888
Austin Schuh2f8fd752020-09-01 22:38:28 -0700889 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800890 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700891 // TODO(austin): std::move channel_data in and make that efficient in
892 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800893 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800894 } else if (state->found_last_message() ||
895 (!ignore_missing_data_ &&
896 // When starting up, we can have data which was sent before
897 // the log starts, but the timestamp was after the log
898 // starts. This is unreasonable to avoid, so ignore the
899 // missing data.
900 timestamped_message.monotonic_remote_time.time >=
901 state->monotonic_remote_start_time(
902 timestamped_message.monotonic_remote_time.boot,
903 timestamped_message.channel_index) &&
904 !FLAGS_skip_missing_forwarding_entries)) {
905 if (!state->found_last_message()) {
906 // We've found a timestamp without data that we expect to have data
907 // for. This likely means that we are at the end of the log file.
908 // Record it and CHECK that in the rest of the log file, we don't find
909 // any more data on that channel. Not all channels will end at the
910 // same point in time since they can be in different files.
911 VLOG(1) << "Found the last message on channel "
912 << timestamped_message.channel_index << ", "
913 << configuration::CleanedChannelToString(
914 logged_configuration()->channels()->Get(
915 timestamped_message.channel_index))
916 << " on node " << MaybeNodeName(state->event_loop()->node())
917 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -0800918
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800919 // The user might be working with log files from 1 node but forgot to
920 // configure the infrastructure to log data for a remote channel on
921 // that node. That can be very hard to debug, even though the log
922 // reader is doing the right thing. At least log a warning in that
923 // case and tell the user what is happening so they can either update
924 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -0700925 const std::vector<std::string> logger_nodes =
926 FindLoggerNodes(log_files_);
927 if (logger_nodes.size()) {
928 // We have old logs which don't have the logger nodes logged. In
929 // that case, we can't be helpful :(
930 bool data_logged = false;
931 const Channel *channel = logged_configuration()->channels()->Get(
932 timestamped_message.channel_index);
933 for (const std::string &node : logger_nodes) {
934 data_logged |=
935 configuration::ChannelMessageIsLoggedOnNode(channel, node);
936 }
937 if (!data_logged) {
938 LOG(WARNING) << "Got a timestamp without any logfiles which "
939 "could contain data for channel "
940 << configuration::CleanedChannelToString(channel);
941 LOG(WARNING) << "Only have logs logged on ["
942 << absl::StrJoin(logger_nodes, ", ") << "]";
943 LOG(WARNING)
944 << "Dropping the rest of the data on "
945 << state->event_loop()->node()->name()->string_view();
946 LOG(WARNING)
947 << "Consider using --skip_missing_forwarding_entries to "
948 "bypass this, update your config to log it, or add data "
949 "from one of the nodes it is logged on.";
950 }
951 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800952 // Now that we found the end of one channel, artificially stop the
953 // rest by setting the found_last_message bit. It is confusing when
954 // part of your data gets replayed but not all. The rest of them will
955 // get dropped as they are replayed to keep memory usage down.
956 state->SetFoundLastMessage(true);
957
958 // Vector storing if we've seen a nullptr message or not per channel.
959 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -0700960 }
961
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800962 // Make sure that once we have seen the last message on a channel,
963 // data doesn't start back up again. If the user wants to play
964 // through events like this, they can set
965 // --skip_missing_forwarding_entries or ignore_missing_data_.
966 if (timestamped_message.data == nullptr) {
967 state->set_last_message(timestamped_message.channel_index);
968 } else {
969 if (state->last_message(timestamped_message.channel_index)) {
970 LOG(FATAL) << "Found missing data in the middle of the log file on "
971 "channel "
972 << timestamped_message.channel_index << " "
973 << configuration::StrippedChannelToString(
974 logged_configuration()->channels()->Get(
975 timestamped_message.channel_index))
976 << " " << timestamped_message << " "
977 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -0800978 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800979 }
Austin Schuh92547522019-12-28 14:33:43 -0800980 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800981 } else {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700982 LOG(WARNING) << "Not sending data from before the start of the log file. "
983 << timestamped_message.monotonic_event_time.time
984 .time_since_epoch()
985 .count()
986 << " start "
987 << monotonic_start_time().time_since_epoch().count() << " "
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700988 << *timestamped_message.data;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800989 }
990
Austin Schuh58646e22021-08-23 23:51:46 -0700991 const BootTimestamp next_time = state->OldestMessageTime();
992 if (next_time != BootTimestamp::max_time()) {
993 if (next_time.boot != state->boot_count()) {
994 VLOG(1) << "Next message for "
995 << MaybeNodeName(state->event_loop()->node())
996 << "is on the next boot, " << next_time << " now is "
997 << state->monotonic_now();
998 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800999 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001000 return;
1001 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001002 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
Austin Schuh58646e22021-08-23 23:51:46 -07001003 << "wakeup for " << next_time.time << "("
1004 << state->ToDistributedClock(next_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001005 << " distributed), now is " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001006 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001007 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001008 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1009 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001010 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 // Set a timer up immediately after now to die. If we don't do this,
1012 // then the senders waiting on the message we just read will never get
1013 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001014 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001015 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1016 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001017 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001018 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001019
Austin Schuh2f8fd752020-09-01 22:38:28 -07001020 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1021 << state->event_loop()->context().monotonic_event_time << " now "
1022 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001023 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001024
Austin Schuh58646e22021-08-23 23:51:46 -07001025 if (state->OldestMessageTime() != BootTimestamp::max_time()) {
1026 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001027 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1028 if (start_time_ != realtime_clock::min_time) {
1029 state->SetStartTimeFlag(start_time_);
1030 }
1031 if (end_time_ != realtime_clock::max_time) {
1032 state->SetEndTimeFlag(end_time_);
1033 }
Austin Schuh58646e22021-08-23 23:51:46 -07001034 event_loop->OnRun([state]() {
1035 BootTimestamp next_time = state->OldestMessageTime();
1036 CHECK_EQ(next_time.boot, state->boot_count());
1037 state->Setup(next_time.time);
1038 state->SetupStartupTimer();
1039 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001040 }
1041}
1042
Austin Schuhe33c08d2022-02-03 18:15:21 -08001043void LogReader::SetEndTime(std::string end_time) {
1044 if (end_time.empty()) {
1045 SetEndTime(realtime_clock::max_time);
1046 } else {
1047 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1048 aos::realtime_clock::FromString(end_time);
1049 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1050 << "'. Expected a date in the format of "
1051 "2021-01-15_15-30-35.000000000.";
1052 SetEndTime(*parsed_end_time);
1053 }
1054}
1055
1056void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1057 end_time_ = end_time;
1058}
1059
1060void LogReader::SetStartTime(std::string start_time) {
1061 if (start_time.empty()) {
1062 SetStartTime(realtime_clock::min_time);
1063 } else {
1064 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1065 aos::realtime_clock::FromString(start_time);
1066 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1067 << "'. Expected a date in the format of "
1068 "2021-01-15_15-30-35.000000000.";
1069 SetStartTime(*parsed_start_time);
1070 }
1071}
1072
1073void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1074 start_time_ = start_time;
1075}
1076
Austin Schuhe309d2a2019-11-29 13:25:21 -08001077void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001078 // Make sure that things get destroyed in the correct order, rather than
1079 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001080 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001081 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001082 }
Austin Schuh92547522019-12-28 14:33:43 -08001083
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001084 event_loop_factory_unique_ptr_.reset();
1085 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001086}
1087
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001088void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001089 std::string_view add_prefix,
1090 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001091 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1092 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1093 if (channel->name()->str() == name &&
1094 channel->type()->string_view() == type) {
1095 CHECK_EQ(0u, remapped_channels_.count(ii))
1096 << "Already remapped channel "
1097 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001098 RemappedChannel remapped_channel;
1099 remapped_channel.remapped_name =
1100 std::string(add_prefix) + std::string(name);
1101 remapped_channel.new_type = new_type;
1102 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001103 VLOG(1) << "Remapping channel "
1104 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001105 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001106 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001107 return;
1108 }
1109 }
1110 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1111 << type;
1112}
1113
Austin Schuh01b4c352020-09-21 23:09:39 -07001114void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1115 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001116 std::string_view add_prefix,
1117 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001118 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1119 const Channel *remapped_channel =
1120 configuration::GetChannel(logged_configuration(), name, type, "", node);
1121 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1122 << "\", \"type\": \"" << type << "\"}";
1123 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1124 << "\"}";
1125 VLOG(1) << "Remapped "
1126 << aos::configuration::StrippedChannelToString(remapped_channel);
1127
1128 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1129 // we want it to degrade if the heuristics fail to just work.
1130 //
1131 // The easiest way to do this is going to be incredibly specific and verbose.
1132 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1133 // /original/0/spray. Then, create a map from /original/spray to
1134 // /original/0/spray for just the type we were asked for.
1135 if (name != remapped_channel->name()->string_view()) {
1136 MapT new_map;
1137 new_map.match = std::make_unique<ChannelT>();
1138 new_map.match->name = absl::StrCat(add_prefix, name);
1139 new_map.match->type = type;
1140 if (node != nullptr) {
1141 new_map.match->source_node = node->name()->str();
1142 }
1143 new_map.rename = std::make_unique<ChannelT>();
1144 new_map.rename->name =
1145 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1146 maps_.emplace_back(std::move(new_map));
1147 }
1148
1149 const size_t channel_index =
1150 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1151 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1152 << "Already remapped channel "
1153 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001154
1155 RemappedChannel remapped_channel_struct;
1156 remapped_channel_struct.remapped_name =
1157 std::string(add_prefix) +
1158 std::string(remapped_channel->name()->string_view());
1159 remapped_channel_struct.new_type = new_type;
1160 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001161 MakeRemappedConfig();
1162}
1163
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001164void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001165 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001166 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001167 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001168 << ": Can't change the mapping after the events are scheduled.";
1169 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001170 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001171
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001172 // If no remapping occurred and we are using the original config, then there
1173 // is nothing interesting to do here.
1174 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001175 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001176 return;
1177 }
1178 // Config to copy Channel definitions from. Use the specified
1179 // replay_configuration_ if it has been provided.
1180 const Configuration *const base_config = replay_configuration_ == nullptr
1181 ? logged_configuration()
1182 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001183
1184 // Create a config with all the channels, but un-sorted/merged. Collect up
1185 // the schemas while we do this. Call MergeConfiguration to sort everything,
1186 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001187
1188 // This is the builder that we use for the config containing all the new
1189 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001190 flatbuffers::FlatBufferBuilder fbb;
1191 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001192 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001193
1194 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1195 << ": Merging logic needs to be updated when the number of channel "
1196 "fields changes.";
1197
1198 // List of schemas.
1199 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1200 // Make sure our new RemoteMessage schema is in there for old logs without it.
1201 schema_map.insert(std::make_pair(
1202 RemoteMessage::GetFullyQualifiedName(),
1203 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1204 message_bridge::RemoteMessageSchema()))));
1205
1206 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001207 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001208 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001209 base_config, logged_configuration()->channels()->Get(pair.first), "",
1210 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001211 channel_offsets.emplace_back(
1212 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001213
1214 if (c->has_destination_nodes()) {
1215 for (const Connection *connection : *c->destination_nodes()) {
1216 switch (connection->timestamp_logger()) {
1217 case LoggerConfig::LOCAL_LOGGER:
1218 case LoggerConfig::NOT_LOGGED:
1219 // There is no timestamp channel associated with this, so ignore it.
1220 break;
1221
1222 case LoggerConfig::REMOTE_LOGGER:
1223 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1224 // We want to make a split timestamp channel regardless of what type
1225 // of log this used to be. No sense propagating the single
1226 // timestamp channel.
1227
1228 CHECK(connection->has_timestamp_logger_nodes());
1229 for (const flatbuffers::String *timestamp_logger_node :
1230 *connection->timestamp_logger_nodes()) {
1231 const Node *node = configuration::GetNode(
1232 logged_configuration(), timestamp_logger_node->string_view());
1233 message_bridge::ChannelTimestampFinder finder(
1234 logged_configuration(), "log_reader", node);
1235
1236 // We are assuming here that all the maps are setup correctly to
1237 // handle arbitrary timestamps. Apply the maps for this node to
1238 // see what name this ends up with.
1239 std::string name = finder.SplitChannelName(
1240 pair.second.remapped_name, c->type()->str(), connection);
1241 std::string unmapped_name = name;
1242 configuration::HandleMaps(logged_configuration()->maps(), &name,
1243 "aos.message_bridge.RemoteMessage",
1244 node);
1245 CHECK_NE(name, unmapped_name)
1246 << ": Remote timestamp channel was not remapped, this is "
1247 "very fishy";
1248 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1249 fbb.CreateString(name);
1250 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1251 fbb.CreateString("aos.message_bridge.RemoteMessage");
1252 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1253 fbb.CreateString(timestamp_logger_node->string_view());
1254
1255 // Now, build a channel. Don't log it, 2 senders, and match the
1256 // source frequency.
1257 Channel::Builder channel_builder(fbb);
1258 channel_builder.add_name(channel_name_offset);
1259 channel_builder.add_type(channel_type_offset);
1260 channel_builder.add_source_node(source_node_offset);
1261 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1262 channel_builder.add_num_senders(2);
1263 if (c->has_frequency()) {
1264 channel_builder.add_frequency(c->frequency());
1265 }
1266 channel_offsets.emplace_back(channel_builder.Finish());
1267 }
1268 break;
1269 }
1270 }
1271 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001272 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001273
Austin Schuh0de30f32020-12-06 12:44:28 -08001274 // Now reconstruct the original channels, translating types as needed
1275 for (const Channel *c : *base_config->channels()) {
1276 // Search for a mapping channel.
1277 std::string_view new_type = "";
1278 for (auto &pair : remapped_channels_) {
1279 const Channel *const remapped_channel =
1280 logged_configuration()->channels()->Get(pair.first);
1281 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1282 remapped_channel->type()->string_view() == c->type()->string_view()) {
1283 new_type = pair.second.new_type;
1284 break;
1285 }
1286 }
1287
1288 // Copy everything over.
1289 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1290
1291 // Add the schema if it doesn't exist.
1292 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1293 CHECK(c->has_schema());
1294 schema_map.insert(std::make_pair(c->type()->string_view(),
1295 RecursiveCopyFlatBuffer(c->schema())));
1296 }
1297 }
1298
1299 // The MergeConfiguration API takes a vector, not a map. Convert.
1300 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1301 while (!schema_map.empty()) {
1302 schemas.emplace_back(std::move(schema_map.begin()->second));
1303 schema_map.erase(schema_map.begin());
1304 }
1305
1306 // Create the Configuration containing the new channels that we want to add.
1307 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1308 channels_offset =
1309 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1310
1311 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001312 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001313 if (base_config->maps()) {
1314 for (const Map *map : *base_config->maps()) {
1315 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1316 }
1317 }
1318
1319 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001320 for (const MapT &map : maps_) {
1321 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001322 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001323 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001324 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001325 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001326 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001327 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1328 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001329 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001330 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001331 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001332 match_builder.add_name(match_name_offset);
1333 match_builder.add_type(match_type_offset);
1334 if (!map.match->source_node.empty()) {
1335 match_builder.add_source_node(match_source_node_offset);
1336 }
1337 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1338
Austin Schuh0de30f32020-12-06 12:44:28 -08001339 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001340 rename_builder.add_name(rename_name_offset);
1341 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1342
Austin Schuh0de30f32020-12-06 12:44:28 -08001343 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001344 map_builder.add_match(match_offset);
1345 map_builder.add_rename(rename_offset);
1346 map_offsets.emplace_back(map_builder.Finish());
1347 }
1348
Austin Schuh0de30f32020-12-06 12:44:28 -08001349 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1350 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001351
Austin Schuh0de30f32020-12-06 12:44:28 -08001352 // And copy everything else over.
1353 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1354 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1355
1356 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1357 applications_offset =
1358 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1359
1360 // Now insert everything else in unmodified.
1361 ConfigurationBuilder configuration_builder(fbb);
1362 if (!channels_offset.IsNull()) {
1363 configuration_builder.add_channels(channels_offset);
1364 }
1365 if (!maps_offsets.IsNull()) {
1366 configuration_builder.add_maps(maps_offsets);
1367 }
1368 if (!nodes_offset.IsNull()) {
1369 configuration_builder.add_nodes(nodes_offset);
1370 }
1371 if (!applications_offset.IsNull()) {
1372 configuration_builder.add_applications(applications_offset);
1373 }
1374
1375 if (base_config->has_channel_storage_duration()) {
1376 configuration_builder.add_channel_storage_duration(
1377 base_config->channel_storage_duration());
1378 }
1379
1380 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1381 << ": Merging logic needs to be updated when the number of configuration "
1382 "fields changes.";
1383
1384 fbb.Finish(configuration_builder.Finish());
1385
1386 // Clean it up and return it! By using MergeConfiguration here, we'll
1387 // actually get a deduplicated config for free too.
1388 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1389 configuration::MergeConfiguration(
1390 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1391
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001392 remapped_configuration_buffer_ =
1393 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001394 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001395
1396 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001397
1398 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001399}
1400
Austin Schuh1c227352021-09-17 12:53:54 -07001401std::vector<const Channel *> LogReader::RemappedChannels() const {
1402 std::vector<const Channel *> result;
1403 result.reserve(remapped_channels_.size());
1404 for (auto &pair : remapped_channels_) {
1405 const Channel *const logged_channel =
1406 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1407
1408 auto channel_iterator = std::lower_bound(
1409 remapped_configuration_->channels()->cbegin(),
1410 remapped_configuration_->channels()->cend(),
1411 std::make_pair(std::string_view(pair.second.remapped_name),
1412 logged_channel->type()->string_view()),
1413 CompareChannels);
1414
1415 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1416 CHECK(EqualsChannels(
1417 *channel_iterator,
1418 std::make_pair(std::string_view(pair.second.remapped_name),
1419 logged_channel->type()->string_view())));
1420 result.push_back(*channel_iterator);
1421 }
1422 return result;
1423}
1424
Austin Schuh6f3babe2020-01-26 20:34:50 -08001425const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001426 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001427 const Channel *channel) {
1428 std::string_view channel_name = channel->name()->string_view();
1429 std::string_view channel_type = channel->type()->string_view();
1430 const int channel_index =
1431 configuration::ChannelIndex(logged_configuration(), channel);
1432 // If the channel is remapped, find the correct channel name to use.
1433 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001434 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001435 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001436 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001437 }
1438
Austin Schuhee711052020-08-24 16:06:09 -07001439 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001440 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001441 configuration(), channel_name, channel_type,
1442 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001443
1444 CHECK(remapped_channel != nullptr)
1445 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1446 << channel_type << "\"} because it is not in the provided configuration.";
1447
1448 return remapped_channel;
1449}
1450
Austin Schuh58646e22021-08-23 23:51:46 -07001451LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper,
1452 const Node *node)
1453 : timestamp_mapper_(std::move(timestamp_mapper)), node_(node) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001454
1455void LogReader::State::AddPeer(State *peer) {
1456 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1457 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1458 }
1459}
Austin Schuh858c9f32020-08-31 16:56:12 -07001460
Austin Schuh58646e22021-08-23 23:51:46 -07001461void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001462 NodeEventLoopFactory *node_event_loop_factory,
1463 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001464 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001465 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001466}
1467
1468void LogReader::State::SetChannelCount(size_t count) {
1469 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001470 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001471 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001472 channel_source_state_.resize(count);
1473 factory_channel_index_.resize(count);
1474 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001475}
1476
Austin Schuh58646e22021-08-23 23:51:46 -07001477void LogReader::State::SetRemoteTimestampSender(
1478 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1479 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1480}
1481
Austin Schuh858c9f32020-08-31 16:56:12 -07001482void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001483 size_t logged_channel_index, size_t factory_channel_index,
1484 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001485 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1486 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001487 channels_[logged_channel_index] = std::move(sender);
1488 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001489 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001490
Austin Schuh58646e22021-08-23 23:51:46 -07001491 if (is_forwarded) {
1492 queue_index_map_[logged_channel_index] =
1493 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001494 }
1495
1496 factory_channel_index_[logged_channel_index] = factory_channel_index;
1497}
1498
Austin Schuh287d43d2020-12-04 20:19:33 -08001499bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1500 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001501 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001502 uint32_t remote_queue_index = 0xffffffff;
1503
Austin Schuh287d43d2020-12-04 20:19:33 -08001504 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001505 State *source_state =
1506 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001507 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001508 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001509 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001510
Austin Schuh9942bae2021-01-07 22:06:44 -08001511 struct SentTimestamp {
1512 monotonic_clock::time_point monotonic_event_time;
1513 uint32_t queue_index;
1514 } search;
1515
Austin Schuh58646e22021-08-23 23:51:46 -07001516 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1517 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001518 search.monotonic_event_time =
1519 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001520 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001521
1522 // Find the sent time if available.
1523 auto element = std::lower_bound(
1524 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001525 [](ContiguousSentTimestamp a, SentTimestamp b) {
1526 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001527 return true;
1528 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001529 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001530 return false;
1531 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001532
1533 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001534 return true;
1535 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001536 if (a.starting_queue_index >= b.queue_index) {
1537 return false;
1538 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001539
Austin Schuh9942bae2021-01-07 22:06:44 -08001540 // If it isn't clearly below or above, it is below. Since we return
1541 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001542 return false;
1543 });
1544
1545 // TODO(austin): Be a bit more principled here, but we will want to do that
1546 // after the logger rewrite. We hit this when one node finishes, but the
1547 // other node isn't done yet. So there is no send time, but there is a
1548 // receive time.
1549 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001550 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1551 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001552
1553 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001554 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001555 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001556 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001557 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001558 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001559 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001560 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001561
Austin Schuh58646e22021-08-23 23:51:46 -07001562 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001563 element->actual_queue_index -
1564 element->starting_queue_index;
1565 } else {
1566 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001567 }
Austin Schuh58646e22021-08-23 23:51:46 -07001568 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1569 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001570 }
1571
1572 // Send! Use the replayed queue index here instead of the logged queue index
1573 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001574 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001575 RawSender::SharedSpan(timestamped_message.data,
1576 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001577 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001578 timestamped_message.realtime_remote_time, remote_queue_index,
1579 (channel_source_state_[timestamped_message.channel_index] != nullptr
1580 ? CHECK_NOTNULL(
1581 channel_source_state_[timestamped_message.channel_index])
1582 ->event_loop_->boot_uuid()
1583 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001584 if (err != RawSender::Error::kOk) return false;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001585
Austin Schuh287d43d2020-12-04 20:19:33 -08001586 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001587 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001588 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1589 // Nothing here, start a range with 0 length.
1590 ContiguousSentTimestamp timestamp;
1591 timestamp.starting_monotonic_event_time =
1592 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001593 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001594 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001595 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001596 timestamp.actual_queue_index = sender->sent_queue_index();
1597 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1598 timestamp);
1599 } else {
1600 // We've got something. See if the next timestamp is still contiguous. If
1601 // so, grow it.
1602 ContiguousSentTimestamp *back =
1603 &queue_index_map_[timestamped_message.channel_index]->back();
1604 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001605 (timestamped_message.queue_index.index -
1606 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001607 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001608 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001609 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001610 } else {
1611 // Otherwise, make a new one.
1612 ContiguousSentTimestamp timestamp;
1613 timestamp.starting_monotonic_event_time =
1614 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001615 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001616 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001617 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001618 timestamp.actual_queue_index = sender->sent_queue_index();
1619 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1620 timestamp);
1621 }
1622 }
1623
1624 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1625 // queue index diverge a couple of elements, which would be a very small
1626 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001627 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1628 nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001629 State *source_state =
1630 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1631
Austin Schuh969cd602021-01-03 00:09:45 -08001632 flatbuffers::FlatBufferBuilder fbb;
1633 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001634 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1635 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001636
Austin Schuh969cd602021-01-03 00:09:45 -08001637 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001638
1639 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001640 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001641
1642 // Swap the remote and sent metrics. They are from the sender's
1643 // perspective, not the receiver's perspective.
1644 message_header_builder.add_monotonic_sent_time(
1645 sender->monotonic_sent_time().time_since_epoch().count());
1646 message_header_builder.add_realtime_sent_time(
1647 sender->realtime_sent_time().time_since_epoch().count());
1648 message_header_builder.add_queue_index(sender->sent_queue_index());
1649
Austin Schuh58646e22021-08-23 23:51:46 -07001650 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1651 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001652 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001653 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1654 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001655 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001656 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001657
1658 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001659 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001660
Austin Schuh969cd602021-01-03 00:09:45 -08001661 fbb.Finish(message_header_builder.Finish());
1662
1663 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1664 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001665 timestamped_message.monotonic_timestamp_time,
1666 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001667 }
1668
1669 return true;
1670}
1671
Austin Schuh969cd602021-01-03 00:09:45 -08001672LogReader::RemoteMessageSender::RemoteMessageSender(
1673 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1674 : event_loop_(event_loop),
1675 sender_(std::move(sender)),
1676 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1677
1678void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1679 if (remote_timestamps_.empty()) {
1680 CHECK_NOTNULL(timer_);
1681 timer_->Disable();
1682 scheduled_time_ = monotonic_clock::min_time;
1683 return;
1684 }
1685
1686 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1687 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001688 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001689 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001690 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1691 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001692 }
1693}
1694
1695void LogReader::RemoteMessageSender::Send(
1696 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001697 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001698 // There are 2 variants of logs.
1699 // 1) Logs without monotonic_timestamp_time
1700 // 2) Logs with monotonic_timestamp_time
1701 //
1702 // As of Jan 2021, we shouldn't have any more logs without
1703 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1704 // the effort of saving.
1705 //
1706 // This gives us 3 cases, 2 of which are undistinguishable.
1707 // 1) Old log without monotonic_timestamp_time.
1708 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1709 // remotely so we actually have monotonic_timestamp_time.
1710 // 3) New log, but the timestamp was logged on the node receiving the message
1711 // so there is no monotonic_timestamp_time.
1712 //
1713 // Our goal when replaying is to accurately reproduce the state of the world
1714 // present when logging. If a timestamp wasn't sent back across the network,
1715 // we shouldn't replay one back across the network.
1716 //
1717 // Given that we don't really care about 1, we can use the presence of the
1718 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1719 // monotonic_timestamp_time, this means the message was logged locally and
1720 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001721 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001722 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001723 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001724
Austin Schuh58646e22021-08-23 23:51:46 -07001725 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
1726
Austin Schuhc41d6a82021-07-16 14:49:23 -07001727 remote_timestamps_.emplace(
1728 std::upper_bound(
1729 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07001730 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07001731 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1732 const Timestamp &timestamp) {
1733 return monotonic_timestamp_time <
1734 timestamp.monotonic_timestamp_time;
1735 }),
Austin Schuh58646e22021-08-23 23:51:46 -07001736 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07001737 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001738}
1739
1740void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001741 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1742 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001743 CHECK(!remote_timestamps_.empty());
1744
1745 // Send out all timestamps at the currently scheduled time.
1746 while (remote_timestamps_.front().monotonic_timestamp_time ==
1747 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07001748 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
1749 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08001750 remote_timestamps_.pop_front();
1751 if (remote_timestamps_.empty()) {
1752 break;
1753 }
1754 }
1755 scheduled_time_ = monotonic_clock::min_time;
1756
1757 ScheduleTimestamp();
1758}
1759
1760LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001761 const Channel *channel, const Connection *connection) {
1762 message_bridge::ChannelTimestampFinder finder(event_loop_);
1763 // Look at any pre-created channel/connection pairs.
1764 {
1765 auto it =
1766 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1767 if (it != channel_timestamp_loggers_.end()) {
1768 return it->second.get();
1769 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001770 }
1771
Austin Schuh61e973f2021-02-21 21:43:56 -08001772 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1773 // to.
1774 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1775
1776 {
1777 // See if that has been created before. If so, cache it in
1778 // channel_timestamp_loggers_ and return.
1779 auto it = timestamp_loggers_.find(timestamp_channel);
1780 if (it != timestamp_loggers_.end()) {
1781 CHECK(channel_timestamp_loggers_
1782 .try_emplace(std::make_pair(channel, connection), it->second)
1783 .second);
1784 return it->second.get();
1785 }
1786 }
1787
1788 // Otherwise, make a sender, save it, and cache it.
1789 auto result = channel_timestamp_loggers_.try_emplace(
1790 std::make_pair(channel, connection),
1791 std::make_shared<RemoteMessageSender>(
1792 event_loop()->MakeSender<RemoteMessage>(
1793 timestamp_channel->name()->string_view()),
1794 event_loop()));
1795
1796 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1797 .second);
1798 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001799}
1800
Austin Schuhdda74ec2021-01-03 19:30:37 -08001801TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001802 CHECK(timestamp_mapper_ != nullptr);
1803 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1804 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001805
Austin Schuhe639ea12021-01-25 13:00:22 -08001806 TimestampedMessage result = std::move(*result_ptr);
1807
Austin Schuh2f8fd752020-09-01 22:38:28 -07001808 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001809 << result.monotonic_event_time;
1810 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001811 SeedSortedMessages();
1812
Austin Schuh58646e22021-08-23 23:51:46 -07001813 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001814
Austin Schuh5ee56872021-01-30 16:53:34 -08001815 VLOG(1) << "Popped " << result
1816 << configuration::CleanedChannelToString(
1817 event_loop_->configuration()->channels()->Get(
1818 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001819 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001820}
1821
Austin Schuhe33c08d2022-02-03 18:15:21 -08001822BootTimestamp LogReader::State::OldestMessageTime() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001823 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001824 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08001825 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001826 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1827 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001828 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08001829 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08001830 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001831 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001832
1833 if (result_ptr->monotonic_event_time.boot == boot_count()) {
1834 ObserveNextMessage(result_ptr->monotonic_event_time.time,
1835 result_ptr->realtime_event_time);
1836 }
1837
Austin Schuh58646e22021-08-23 23:51:46 -07001838 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001839}
1840
1841void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001842 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001843
Austin Schuhe639ea12021-01-25 13:00:22 -08001844 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1845 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001846}
1847
1848void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07001849 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001850 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001851 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001852 for (size_t i = 0; i < channels_.size(); ++i) {
1853 channels_[i].reset();
1854 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08001855 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08001856 channel_timestamp_loggers_.clear();
1857 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001858 event_loop_unique_ptr_.reset();
1859 event_loop_ = nullptr;
1860 timer_handler_ = nullptr;
1861 node_event_loop_factory_ = nullptr;
1862}
1863
Austin Schuhe33c08d2022-02-03 18:15:21 -08001864void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
1865 if (start_time != realtime_clock::min_time) {
1866 start_event_notifier_ = std::make_unique<EventNotifier>(
1867 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
1868 }
1869}
1870
1871void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
1872 if (end_time != realtime_clock::max_time) {
1873 end_event_notifier_ = std::make_unique<EventNotifier>(
1874 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
1875 }
1876}
1877
1878void LogReader::State::ObserveNextMessage(
1879 monotonic_clock::time_point monotonic_event,
1880 realtime_clock::time_point realtime_event) {
1881 if (start_event_notifier_) {
1882 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
1883 }
1884 if (end_event_notifier_) {
1885 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
1886 }
1887}
1888
1889void LogReader::State::ClearTimeFlags() {
1890 start_event_notifier_.reset();
1891 end_event_notifier_.reset();
1892}
1893
1894void LogReader::State::NotifyLogfileStart() {
1895 if (start_event_notifier_) {
1896 if (start_event_notifier_->realtime_event_time() >
1897 realtime_start_time(boot_count())) {
1898 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
1899 << " > " << realtime_start_time(boot_count());
1900 return;
1901 }
1902 }
1903 if (found_last_message_) {
1904 VLOG(1) << "Last message already found, bailing";
1905 return;
1906 }
1907 RunOnStart();
1908}
1909
1910void LogReader::State::NotifyFlagStart() {
1911 if (start_event_notifier_->realtime_event_time() >=
1912 realtime_start_time(boot_count())) {
1913 RunOnStart();
1914 }
1915}
1916
1917void LogReader::State::NotifyLogfileEnd() {
1918 if (found_last_message_) {
1919 return;
1920 }
1921
1922 if (!stopped_ && started_) {
1923 RunOnEnd();
1924 }
1925}
1926
1927void LogReader::State::NotifyFlagEnd() {
1928 if (!stopped_ && started_) {
1929 RunOnEnd();
1930 SetFoundLastMessage(true);
1931 }
1932}
1933
Austin Schuhe309d2a2019-11-29 13:25:21 -08001934} // namespace logger
1935} // namespace aos