blob: 1c3a349a6ea450db454e8866892e9d5ba26da8c3 [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.
Austin Schuh349e7ad2022-04-02 21:12:26 -0700279 LOG(WARNING) << "Failed to find channel "
280 << finder.SplitChannelName(channel, connection)
281 << " on node " << aos::FlatbufferToJson(node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800282 remote_nodes.insert(connection->name()->string_view());
283 }
284 }
285 }
286
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700287 std::vector<const Node *> timestamp_logger_nodes =
288 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800289 for (const std::string_view remote_node : remote_nodes) {
290 const std::string channel = finder.CombinedChannelName(remote_node);
291
Austin Schuh0de30f32020-12-06 12:44:28 -0800292 // See if the log file is an old log with MessageHeader channels in it, or
293 // a newer log with RemoteMessage. If we find an older log, rename the
294 // type too along with the name.
295 if (HasChannel<MessageHeader>(channel, node)) {
296 CHECK(!HasChannel<RemoteMessage>(channel, node))
297 << ": Can't have both a MessageHeader and RemoteMessage remote "
298 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800299 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
300 // careful about updating the config, but there are fewer and fewer logs
301 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800302 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
303 "aos.message_bridge.RemoteMessage");
304 } else {
305 CHECK(HasChannel<RemoteMessage>(channel, node))
306 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
307 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
308 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800309 // Only bother to remap if there's something on the channel. We can
310 // tell if the channel was marked NOT_LOGGED or not. This makes the
311 // config not change un-necesarily when we replay a log with NOT_LOGGED
312 // messages.
313 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
314 RemapLoggedChannel<RemoteMessage>(channel, node);
315 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800316 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700317 }
318 }
319
Austin Schuh6aa77be2020-02-22 21:06:40 -0800320 if (replay_configuration) {
321 CHECK_EQ(configuration::MultiNode(configuration()),
322 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700323 << ": Log file and replay config need to both be multi or single "
324 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800325 }
326
Austin Schuh6f3babe2020-01-26 20:34:50 -0800327 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800328 states_.emplace_back(std::make_unique<State>(
Austin Schuh58646e22021-08-23 23:51:46 -0700329 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, "")),
330 nullptr));
Austin Schuh8bd96322020-02-13 21:18:22 -0800331 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800332 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700333 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800334 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700335 << ": Log file and replay config need to have matching nodes "
336 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700337 for (const Node *node : *logged_configuration()->nodes()) {
338 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700339 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
340 << " in logged config that is not present in the replay "
341 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700342 }
343 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800344 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800345 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800346 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800347}
348
Austin Schuh6aa77be2020-02-22 21:06:40 -0800349LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700350 if (event_loop_factory_unique_ptr_) {
351 Deregister();
352 } else if (event_loop_factory_ != nullptr) {
353 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
354 "is destroyed";
355 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700356 // Zero out some buffers. It's easy to do use-after-frees on these, so make
357 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700358 if (remapped_configuration_buffer_) {
359 remapped_configuration_buffer_->Wipe();
360 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800361}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800362
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800363const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800364 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800365}
366
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800367const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800368 return remapped_configuration_;
369}
370
Austin Schuh07676622021-01-21 18:59:17 -0800371std::vector<const Node *> LogReader::LoggedNodes() const {
372 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800373}
Austin Schuh15649d62019-12-28 16:36:38 -0800374
Austin Schuh11d43732020-09-21 17:28:30 -0700375monotonic_clock::time_point LogReader::monotonic_start_time(
376 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800377 State *state =
378 states_[configuration::GetNodeIndex(configuration(), node)].get();
379 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
380
Austin Schuhf665eb42022-02-03 18:26:25 -0800381 return state->monotonic_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800382}
383
Austin Schuh11d43732020-09-21 17:28:30 -0700384realtime_clock::time_point LogReader::realtime_start_time(
385 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800386 State *state =
387 states_[configuration::GetNodeIndex(configuration(), node)].get();
388 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
389
Austin Schuhf665eb42022-02-03 18:26:25 -0800390 return state->realtime_start_time(state->boot_count());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800391}
392
Austin Schuh58646e22021-08-23 23:51:46 -0700393void LogReader::OnStart(std::function<void()> fn) {
394 CHECK(!configuration::MultiNode(configuration()));
395 OnStart(nullptr, std::move(fn));
396}
397
398void LogReader::OnStart(const Node *node, std::function<void()> fn) {
399 const int node_index = configuration::GetNodeIndex(configuration(), node);
400 CHECK_GE(node_index, 0);
401 CHECK_LT(node_index, static_cast<int>(states_.size()));
402 State *state = states_[node_index].get();
403 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
404
405 state->OnStart(std::move(fn));
406}
407
408void LogReader::State::OnStart(std::function<void()> fn) {
409 on_starts_.emplace_back(std::move(fn));
410}
411
412void LogReader::State::RunOnStart() {
413 SetRealtimeOffset(monotonic_start_time(boot_count()),
414 realtime_start_time(boot_count()));
415
416 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
417 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800418 auto fn = [this]() {
419 for (size_t i = 0; i < on_starts_.size(); ++i) {
420 on_starts_[i]();
421 }
422 };
423 if (event_loop_factory_) {
424 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
425 } else {
426 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700427 }
428 stopped_ = false;
429 started_ = true;
430}
431
432void LogReader::OnEnd(std::function<void()> fn) {
433 CHECK(!configuration::MultiNode(configuration()));
434 OnEnd(nullptr, std::move(fn));
435}
436
437void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
438 const int node_index = configuration::GetNodeIndex(configuration(), node);
439 CHECK_GE(node_index, 0);
440 CHECK_LT(node_index, static_cast<int>(states_.size()));
441 State *state = states_[node_index].get();
442 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
443
444 state->OnEnd(std::move(fn));
445}
446
447void LogReader::State::OnEnd(std::function<void()> fn) {
448 on_ends_.emplace_back(std::move(fn));
449}
450
451void LogReader::State::RunOnEnd() {
452 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
453 << monotonic_start_time(boot_count());
Austin Schuhe33c08d2022-02-03 18:15:21 -0800454 auto fn = [this]() {
455 for (size_t i = 0; i < on_ends_.size(); ++i) {
456 on_ends_[i]();
457 }
458 };
459 if (event_loop_factory_) {
460 event_loop_factory_->AllowApplicationCreationDuring(std::move(fn));
461 } else {
462 fn();
Austin Schuh58646e22021-08-23 23:51:46 -0700463 }
464
465 stopped_ = true;
Austin Schuhe33c08d2022-02-03 18:15:21 -0800466 started_ = true;
Austin Schuh58646e22021-08-23 23:51:46 -0700467}
468
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800469void LogReader::Register() {
470 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800471 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800472 Register(event_loop_factory_unique_ptr_.get());
473}
474
Austin Schuh58646e22021-08-23 23:51:46 -0700475void LogReader::RegisterWithoutStarting(
476 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800477 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700478 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800479 filters_ =
480 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800481 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700482 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800483 chrono::duration_cast<chrono::nanoseconds>(
484 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800485
Austin Schuhe639ea12021-01-25 13:00:22 -0800486 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700487 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800488 const size_t node_index =
489 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800490 std::vector<LogParts> filtered_parts = FilterPartsForNode(
491 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800492
Austin Schuh287d43d2020-12-04 20:19:33 -0800493 states_[node_index] = std::make_unique<State>(
494 filtered_parts.size() == 0u
495 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700496 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
497 node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800498 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700499 state->SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -0800500 event_loop_factory_->GetNodeEventLoopFactory(node),
501 event_loop_factory_);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700502
503 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800504 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800505 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800506 filters_->SetTimestampMappers(std::move(timestamp_mappers));
507
508 // Note: this needs to be set before any times are pulled, or we won't observe
509 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800510 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700511
Austin Schuh287d43d2020-12-04 20:19:33 -0800512 for (const Node *node : configuration::GetNodes(configuration())) {
513 const size_t node_index =
514 configuration::GetNodeIndex(configuration(), node);
515 State *state = states_[node_index].get();
516 for (const Node *other_node : configuration::GetNodes(configuration())) {
517 const size_t other_node_index =
518 configuration::GetNodeIndex(configuration(), other_node);
519 State *other_state = states_[other_node_index].get();
520 if (other_state != state) {
521 state->AddPeer(other_state);
522 }
523 }
524 }
525
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700526 // Register after making all the State objects so we can build references
527 // between them.
528 for (const Node *node : configuration::GetNodes(configuration())) {
529 const size_t node_index =
530 configuration::GetNodeIndex(configuration(), node);
531 State *state = states_[node_index].get();
532
Austin Schuh58646e22021-08-23 23:51:46 -0700533 // If we didn't find any log files with data in them, we won't ever get a
534 // callback or be live. So skip the rest of the setup.
535 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
536 continue;
537 }
538 ++live_nodes_;
539
540 NodeEventLoopFactory *node_factory =
541 event_loop_factory_->GetNodeEventLoopFactory(node);
542 node_factory->OnStartup([this, state, node]() {
543 RegisterDuringStartup(state->MakeEventLoop(), node);
544 });
545 node_factory->OnShutdown([this, state, node]() {
546 RegisterDuringStartup(nullptr, node);
547 state->DestroyEventLoop();
548 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700549 }
550
James Kuszmaul46d82582020-05-09 19:50:09 -0700551 if (live_nodes_ == 0) {
552 LOG(FATAL)
553 << "Don't have logs from any of the nodes in the replay config--are "
554 "you sure that the replay config matches the original config?";
555 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800556
Austin Schuh87dd3832021-01-01 23:07:31 -0800557 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800558
Austin Schuh858c9f32020-08-31 16:56:12 -0700559 for (std::unique_ptr<State> &state : states_) {
560 state->SeedSortedMessages();
561 }
562
Austin Schuh6f3babe2020-01-26 20:34:50 -0800563 // Forwarding is tracked per channel. If it is enabled, we want to turn it
564 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700565 // nodes, and also replayed on the other nodes. This may not satisfy all
566 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800567 if (configuration::MultiNode(event_loop_factory_->configuration())) {
568 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
569 const Channel *channel = logged_configuration()->channels()->Get(i);
570 const Node *node = configuration::GetNode(
571 configuration(), channel->source_node()->string_view());
572
Austin Schuh8bd96322020-02-13 21:18:22 -0800573 State *state =
574 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800575
576 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700577 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800578
579 event_loop_factory_->DisableForwarding(remapped_channel);
580 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700581
582 // If we are replaying a log, we don't want a bunch of redundant messages
583 // from both the real message bridge and simulated message bridge.
584 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800585 }
Austin Schuh891214d2021-11-11 20:35:02 -0800586
587 // Write pseudo start times out to file now that we are all setup.
588 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700589}
590
591void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
592 RegisterWithoutStarting(event_loop_factory);
Austin Schuhe33c08d2022-02-03 18:15:21 -0800593 StartAfterRegister(event_loop_factory);
594}
595
596void LogReader::StartAfterRegister(
597 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh58646e22021-08-23 23:51:46 -0700598 // We want to start the log file at the last start time of the log files
599 // from all the nodes. Compute how long each node's simulation needs to run
600 // to move time to this point.
601 distributed_clock::time_point start_time = distributed_clock::min_time;
602
603 // TODO(austin): We want an "OnStart" callback for each node rather than
604 // running until the last node.
605
606 for (std::unique_ptr<State> &state : states_) {
607 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
608 << " for node " << MaybeNodeName(state->node()) << "now "
609 << state->monotonic_now();
610 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
611 continue;
612 }
613 // And start computing the start time on the distributed clock now that
614 // that works.
615 start_time = std::max(
616 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
617 }
618
619 // TODO(austin): If a node doesn't have a start time, we might not queue
620 // enough. If this happens, we'll explode with a frozen error eventually.
621
622 CHECK_GE(start_time, distributed_clock::epoch())
623 << ": Hmm, we have a node starting before the start of time. Offset "
624 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800625
Austin Schuhcde938c2020-02-02 17:30:07 -0800626 // While we are starting the system up, we might be relying on matching data
627 // to timestamps on log files where the timestamp log file starts before the
628 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800629 {
630 const bool prior_ignore_missing_data = ignore_missing_data_;
631 ignore_missing_data_ = true;
632 VLOG(1) << "Running until " << start_time << " in Register";
633 event_loop_factory_->RunFor(start_time.time_since_epoch());
634 VLOG(1) << "At start time";
635 // Now that we are running for real, missing data means that the log file is
636 // corrupted or went wrong.
637 ignore_missing_data_ = prior_ignore_missing_data;
638 }
Austin Schuh92547522019-12-28 14:33:43 -0800639
Austin Schuh8bd96322020-02-13 21:18:22 -0800640 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700641 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700642 if (state->realtime_start_time(0) != realtime_clock::min_time) {
643 state->SetRealtimeOffset(state->monotonic_start_time(0),
644 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700645 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700646 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
647 << " for node " << MaybeNodeName(state->event_loop()->node())
648 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700649 }
650
651 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800652 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800653 }
654}
655
Austin Schuh2f8fd752020-09-01 22:38:28 -0700656message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800657 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800658 if (filters_) {
659 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800660 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800661 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800662}
663
Austin Schuhe309d2a2019-11-29 13:25:21 -0800664void LogReader::Register(EventLoop *event_loop) {
Austin Schuh58646e22021-08-23 23:51:46 -0700665 Register(event_loop, event_loop->node());
666}
667
668void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800669 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700670 states_[configuration::GetNodeIndex(configuration(), node)].get();
671
672 // If we didn't find any log files with data in them, we won't ever get a
673 // callback or be live. So skip the rest of the setup.
674 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
675 return;
676 }
677 ++live_nodes_;
678
679 if (event_loop_factory_ != nullptr) {
680 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
681 [this, event_loop, node]() {
682 RegisterDuringStartup(event_loop, node);
683 });
684 } else {
685 RegisterDuringStartup(event_loop, node);
686 }
687}
688
689void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
690 if (event_loop) {
691 CHECK(event_loop->configuration() == configuration());
692 }
693
694 State *state =
695 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800696
Austin Schuhe33c08d2022-02-03 18:15:21 -0800697 if (!event_loop) {
698 state->ClearTimeFlags();
699 }
700
Austin Schuh858c9f32020-08-31 16:56:12 -0700701 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800702
Tyler Chatow67ddb032020-01-12 14:30:04 -0800703 // We don't run timing reports when trying to print out logged data, because
704 // otherwise we would end up printing out the timing reports themselves...
705 // This is only really relevant when we are replaying into a simulation.
Austin Schuh58646e22021-08-23 23:51:46 -0700706 if (event_loop) {
707 event_loop->SkipTimingReport();
708 event_loop->SkipAosLog();
709 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800710
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700711 for (size_t logged_channel_index = 0;
712 logged_channel_index < logged_configuration()->channels()->size();
713 ++logged_channel_index) {
714 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700715 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700716 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800717
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700718 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh532656d2021-01-11 10:17:18 -0800719
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700721
722 State *source_state = nullptr;
Austin Schuh58646e22021-08-23 23:51:46 -0700723 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
724 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700725 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700726 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800727
Austin Schuh58646e22021-08-23 23:51:46 -0700728 // We've got a message which is being forwarded to this node.
729 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700730
731 source_state =
732 states_[configuration::GetNodeIndex(configuration(), source_node)]
733 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800734 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700735
Austin Schuh58646e22021-08-23 23:51:46 -0700736 // We are the source, and it is forwarded.
737 const bool is_forwarded =
738 configuration::ChannelIsSendableOnNode(channel, node) &&
739 configuration::ConnectionCount(channel);
740
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700741 state->SetChannel(
742 logged_channel_index,
743 configuration::ChannelIndex(configuration(), channel),
744 event_loop && logged ? event_loop->MakeRawSender(channel) : nullptr,
745 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700746
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700747 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700748 const Node *source_node = configuration::GetNode(
749 configuration(), channel->source_node()->string_view());
750
751 for (const Connection *connection : *channel->destination_nodes()) {
752 const bool delivery_time_is_logged =
753 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
754 source_node);
755
756 if (delivery_time_is_logged) {
757 State *destination_state =
758 states_[configuration::GetNodeIndex(
759 configuration(), connection->name()->string_view())]
760 .get();
761 destination_state->SetRemoteTimestampSender(
762 logged_channel_index,
763 event_loop ? state->RemoteTimestampSender(channel, connection)
764 : nullptr);
765 }
766 }
767 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800768 }
769
Austin Schuh58646e22021-08-23 23:51:46 -0700770 if (!event_loop) {
771 state->ClearRemoteTimestampSenders();
772 state->set_timer_handler(nullptr);
773 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800774 return;
775 }
776
Austin Schuh858c9f32020-08-31 16:56:12 -0700777 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700778 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
779 << "at " << state->event_loop()->context().monotonic_event_time
780 << " now " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700781 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800782 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700783 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800784 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800785 event_loop_factory_->Exit();
786 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800787 return;
788 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700789
Austin Schuhdda74ec2021-01-03 19:30:37 -0800790 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700791
792 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
793 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800794
Austin Schuhe309d2a2019-11-29 13:25:21 -0800795 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700796 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700797 if (!FLAGS_skip_order_validation) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700798 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700799 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
800 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800801 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700802 << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700803 } else if (BootTimestamp{.boot = state->boot_count(),
804 .time = monotonic_now} !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700805 timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700806 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800807 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700808 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800809 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700810 << "): " << FlatbufferToJson(state->event_loop()->node())
811 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800812 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700813 << state->DebugString();
814 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800815
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700816 if (timestamped_message.monotonic_event_time.time >
817 state->monotonic_start_time(
818 timestamped_message.monotonic_event_time.boot) ||
Austin Schuh15649d62019-12-28 16:36:38 -0800819 event_loop_factory_ != nullptr) {
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800820 if (timestamped_message.data != nullptr && !state->found_last_message()) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800821 if (timestamped_message.monotonic_remote_time !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700822 BootTimestamp::min_time()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800823 // Confirm that the message was sent on the sending node before the
824 // destination node (this node). As a proxy, do this by making sure
825 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800826 //
827 // TODO(austin): <= means that the cause message (which we know) could
828 // happen after the effect even though we know they are at the same
829 // time. I doubt anyone will notice for a bit, but we should really
830 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -0700831 BootTimestamp monotonic_remote_now =
832 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700833 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -0700834 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -0800835 monotonic_remote_now.boot)
836 << state->event_loop()->node()->name()->string_view() << " to "
837 << state->remote_node(timestamped_message.channel_index)
838 ->name()
839 ->string_view()
840 << " while trying to send a message on "
841 << configuration::CleanedChannelToString(
842 logged_configuration()->channels()->Get(
843 timestamped_message.channel_index))
844 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700845 CHECK_LE(timestamped_message.monotonic_remote_time,
846 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700847 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800848 << state->remote_node(timestamped_message.channel_index)
849 ->name()
850 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800851 << " while trying to send a message on "
852 << configuration::CleanedChannelToString(
853 logged_configuration()->channels()->Get(
854 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700855 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700856 } else if (monotonic_remote_now.boot !=
857 timestamped_message.monotonic_remote_time.boot) {
858 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
859 << " vs "
860 << timestamped_message.monotonic_remote_time.boot;
861 } else if (timestamped_message.monotonic_remote_time >
862 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700863 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800864 << "Check failed: timestamped_message.monotonic_remote_time < "
865 "state->monotonic_remote_now(timestamped_message.channel_"
866 "index) ("
867 << timestamped_message.monotonic_remote_time << " vs. "
868 << state->monotonic_remote_now(
869 timestamped_message.channel_index)
870 << ") " << state->event_loop()->node()->name()->string_view()
871 << " to "
872 << state->remote_node(timestamped_message.channel_index)
873 ->name()
874 ->string_view()
875 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700876 << " ("
877 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700878 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700879 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800880 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700881 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800882 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700883 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700884 << ") " << state->DebugString();
885 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800886 }
887
Austin Schuh15649d62019-12-28 16:36:38 -0800888 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700889 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800890 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800891
Austin Schuh2f8fd752020-09-01 22:38:28 -0700892 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800893 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700894 // TODO(austin): std::move channel_data in and make that efficient in
895 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800896 state->Send(std::move(timestamped_message));
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800897 } else if (state->found_last_message() ||
898 (!ignore_missing_data_ &&
899 // When starting up, we can have data which was sent before
900 // the log starts, but the timestamp was after the log
901 // starts. This is unreasonable to avoid, so ignore the
902 // missing data.
903 timestamped_message.monotonic_remote_time.time >=
904 state->monotonic_remote_start_time(
905 timestamped_message.monotonic_remote_time.boot,
906 timestamped_message.channel_index) &&
907 !FLAGS_skip_missing_forwarding_entries)) {
908 if (!state->found_last_message()) {
909 // We've found a timestamp without data that we expect to have data
910 // for. This likely means that we are at the end of the log file.
911 // Record it and CHECK that in the rest of the log file, we don't find
912 // any more data on that channel. Not all channels will end at the
913 // same point in time since they can be in different files.
914 VLOG(1) << "Found the last message on channel "
915 << timestamped_message.channel_index << ", "
916 << configuration::CleanedChannelToString(
917 logged_configuration()->channels()->Get(
918 timestamped_message.channel_index))
919 << " on node " << MaybeNodeName(state->event_loop()->node())
920 << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -0800921
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800922 // The user might be working with log files from 1 node but forgot to
923 // configure the infrastructure to log data for a remote channel on
924 // that node. That can be very hard to debug, even though the log
925 // reader is doing the right thing. At least log a warning in that
926 // case and tell the user what is happening so they can either update
927 // their config to log the channel or can find a log with the data.
Austin Schuh2bb80e02021-03-20 21:46:17 -0700928 const std::vector<std::string> logger_nodes =
929 FindLoggerNodes(log_files_);
930 if (logger_nodes.size()) {
931 // We have old logs which don't have the logger nodes logged. In
932 // that case, we can't be helpful :(
933 bool data_logged = false;
934 const Channel *channel = logged_configuration()->channels()->Get(
935 timestamped_message.channel_index);
936 for (const std::string &node : logger_nodes) {
937 data_logged |=
938 configuration::ChannelMessageIsLoggedOnNode(channel, node);
939 }
940 if (!data_logged) {
941 LOG(WARNING) << "Got a timestamp without any logfiles which "
942 "could contain data for channel "
943 << configuration::CleanedChannelToString(channel);
944 LOG(WARNING) << "Only have logs logged on ["
945 << absl::StrJoin(logger_nodes, ", ") << "]";
946 LOG(WARNING)
947 << "Dropping the rest of the data on "
948 << state->event_loop()->node()->name()->string_view();
949 LOG(WARNING)
950 << "Consider using --skip_missing_forwarding_entries to "
951 "bypass this, update your config to log it, or add data "
952 "from one of the nodes it is logged on.";
953 }
954 }
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800955 // Now that we found the end of one channel, artificially stop the
956 // rest by setting the found_last_message bit. It is confusing when
957 // part of your data gets replayed but not all. The rest of them will
958 // get dropped as they are replayed to keep memory usage down.
959 state->SetFoundLastMessage(true);
960
961 // Vector storing if we've seen a nullptr message or not per channel.
962 state->set_last_message(timestamped_message.channel_index);
Austin Schuh2bb80e02021-03-20 21:46:17 -0700963 }
964
Austin Schuhbd5f74a2021-11-11 20:55:38 -0800965 // Make sure that once we have seen the last message on a channel,
966 // data doesn't start back up again. If the user wants to play
967 // through events like this, they can set
968 // --skip_missing_forwarding_entries or ignore_missing_data_.
969 if (timestamped_message.data == nullptr) {
970 state->set_last_message(timestamped_message.channel_index);
971 } else {
972 if (state->last_message(timestamped_message.channel_index)) {
973 LOG(FATAL) << "Found missing data in the middle of the log file on "
974 "channel "
975 << timestamped_message.channel_index << " "
976 << configuration::StrippedChannelToString(
977 logged_configuration()->channels()->Get(
978 timestamped_message.channel_index))
979 << " " << timestamped_message << " "
980 << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -0800981 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800982 }
Austin Schuh92547522019-12-28 14:33:43 -0800983 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800984 } else {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700985 LOG(WARNING) << "Not sending data from before the start of the log file. "
986 << timestamped_message.monotonic_event_time.time
987 .time_since_epoch()
988 .count()
989 << " start "
990 << monotonic_start_time().time_since_epoch().count() << " "
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700991 << *timestamped_message.data;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800992 }
993
Austin Schuh58646e22021-08-23 23:51:46 -0700994 const BootTimestamp next_time = state->OldestMessageTime();
995 if (next_time != BootTimestamp::max_time()) {
996 if (next_time.boot != state->boot_count()) {
997 VLOG(1) << "Next message for "
998 << MaybeNodeName(state->event_loop()->node())
999 << "is on the next boot, " << next_time << " now is "
1000 << state->monotonic_now();
1001 CHECK(event_loop_factory_);
Austin Schuhe33c08d2022-02-03 18:15:21 -08001002 state->NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001003 return;
1004 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001005 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
Austin Schuh58646e22021-08-23 23:51:46 -07001006 << "wakeup for " << next_time.time << "("
1007 << state->ToDistributedClock(next_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001008 << " distributed), now is " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -07001009 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001010 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1012 << "No next message, scheduling shutdown";
Austin Schuhe33c08d2022-02-03 18:15:21 -08001013 state->NotifyLogfileEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001014 // Set a timer up immediately after now to die. If we don't do this,
1015 // then the senders waiting on the message we just read will never get
1016 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001017 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001018 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1019 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001020 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001021 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001022
Austin Schuh2f8fd752020-09-01 22:38:28 -07001023 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1024 << state->event_loop()->context().monotonic_event_time << " now "
1025 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001026 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001027
Austin Schuh58646e22021-08-23 23:51:46 -07001028 if (state->OldestMessageTime() != BootTimestamp::max_time()) {
1029 state->set_startup_timer(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001030 event_loop->AddTimer([state]() { state->NotifyLogfileStart(); }));
1031 if (start_time_ != realtime_clock::min_time) {
1032 state->SetStartTimeFlag(start_time_);
1033 }
1034 if (end_time_ != realtime_clock::max_time) {
1035 state->SetEndTimeFlag(end_time_);
1036 }
Austin Schuh58646e22021-08-23 23:51:46 -07001037 event_loop->OnRun([state]() {
1038 BootTimestamp next_time = state->OldestMessageTime();
1039 CHECK_EQ(next_time.boot, state->boot_count());
1040 state->Setup(next_time.time);
1041 state->SetupStartupTimer();
1042 });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001043 }
1044}
1045
Austin Schuhe33c08d2022-02-03 18:15:21 -08001046void LogReader::SetEndTime(std::string end_time) {
1047 if (end_time.empty()) {
1048 SetEndTime(realtime_clock::max_time);
1049 } else {
1050 std::optional<aos::realtime_clock::time_point> parsed_end_time =
1051 aos::realtime_clock::FromString(end_time);
1052 CHECK(parsed_end_time) << ": Failed to parse end time '" << end_time
1053 << "'. Expected a date in the format of "
1054 "2021-01-15_15-30-35.000000000.";
1055 SetEndTime(*parsed_end_time);
1056 }
1057}
1058
1059void LogReader::SetEndTime(realtime_clock::time_point end_time) {
1060 end_time_ = end_time;
1061}
1062
1063void LogReader::SetStartTime(std::string start_time) {
1064 if (start_time.empty()) {
1065 SetStartTime(realtime_clock::min_time);
1066 } else {
1067 std::optional<aos::realtime_clock::time_point> parsed_start_time =
1068 aos::realtime_clock::FromString(start_time);
1069 CHECK(parsed_start_time) << ": Failed to parse start time '" << start_time
1070 << "'. Expected a date in the format of "
1071 "2021-01-15_15-30-35.000000000.";
1072 SetStartTime(*parsed_start_time);
1073 }
1074}
1075
1076void LogReader::SetStartTime(realtime_clock::time_point start_time) {
1077 start_time_ = start_time;
1078}
1079
Austin Schuhe309d2a2019-11-29 13:25:21 -08001080void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001081 // Make sure that things get destroyed in the correct order, rather than
1082 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001083 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001084 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001085 }
Austin Schuh92547522019-12-28 14:33:43 -08001086
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001087 event_loop_factory_unique_ptr_.reset();
1088 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001089}
1090
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001091void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001092 std::string_view add_prefix,
1093 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001094 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1095 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1096 if (channel->name()->str() == name &&
1097 channel->type()->string_view() == type) {
1098 CHECK_EQ(0u, remapped_channels_.count(ii))
1099 << "Already remapped channel "
1100 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001101 RemappedChannel remapped_channel;
1102 remapped_channel.remapped_name =
1103 std::string(add_prefix) + std::string(name);
1104 remapped_channel.new_type = new_type;
1105 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001106 VLOG(1) << "Remapping channel "
1107 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001108 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001109 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001110 return;
1111 }
1112 }
1113 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1114 << type;
1115}
1116
Austin Schuh01b4c352020-09-21 23:09:39 -07001117void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1118 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001119 std::string_view add_prefix,
1120 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001121 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1122 const Channel *remapped_channel =
1123 configuration::GetChannel(logged_configuration(), name, type, "", node);
1124 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1125 << "\", \"type\": \"" << type << "\"}";
1126 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1127 << "\"}";
1128 VLOG(1) << "Remapped "
1129 << aos::configuration::StrippedChannelToString(remapped_channel);
1130
1131 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1132 // we want it to degrade if the heuristics fail to just work.
1133 //
1134 // The easiest way to do this is going to be incredibly specific and verbose.
1135 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1136 // /original/0/spray. Then, create a map from /original/spray to
1137 // /original/0/spray for just the type we were asked for.
1138 if (name != remapped_channel->name()->string_view()) {
1139 MapT new_map;
1140 new_map.match = std::make_unique<ChannelT>();
1141 new_map.match->name = absl::StrCat(add_prefix, name);
1142 new_map.match->type = type;
1143 if (node != nullptr) {
1144 new_map.match->source_node = node->name()->str();
1145 }
1146 new_map.rename = std::make_unique<ChannelT>();
1147 new_map.rename->name =
1148 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1149 maps_.emplace_back(std::move(new_map));
1150 }
1151
1152 const size_t channel_index =
1153 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1154 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1155 << "Already remapped channel "
1156 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001157
1158 RemappedChannel remapped_channel_struct;
1159 remapped_channel_struct.remapped_name =
1160 std::string(add_prefix) +
1161 std::string(remapped_channel->name()->string_view());
1162 remapped_channel_struct.new_type = new_type;
1163 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001164 MakeRemappedConfig();
1165}
1166
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001167void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001168 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001169 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001170 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001171 << ": Can't change the mapping after the events are scheduled.";
1172 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001173 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001174
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001175 // If no remapping occurred and we are using the original config, then there
1176 // is nothing interesting to do here.
1177 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001178 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001179 return;
1180 }
1181 // Config to copy Channel definitions from. Use the specified
1182 // replay_configuration_ if it has been provided.
1183 const Configuration *const base_config = replay_configuration_ == nullptr
1184 ? logged_configuration()
1185 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001186
1187 // Create a config with all the channels, but un-sorted/merged. Collect up
1188 // the schemas while we do this. Call MergeConfiguration to sort everything,
1189 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001190
1191 // This is the builder that we use for the config containing all the new
1192 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001193 flatbuffers::FlatBufferBuilder fbb;
1194 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001195 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001196
1197 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1198 << ": Merging logic needs to be updated when the number of channel "
1199 "fields changes.";
1200
1201 // List of schemas.
1202 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1203 // Make sure our new RemoteMessage schema is in there for old logs without it.
1204 schema_map.insert(std::make_pair(
1205 RemoteMessage::GetFullyQualifiedName(),
1206 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1207 message_bridge::RemoteMessageSchema()))));
1208
1209 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001210 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001211 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001212 base_config, logged_configuration()->channels()->Get(pair.first), "",
1213 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001214 channel_offsets.emplace_back(
1215 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001216
1217 if (c->has_destination_nodes()) {
1218 for (const Connection *connection : *c->destination_nodes()) {
1219 switch (connection->timestamp_logger()) {
1220 case LoggerConfig::LOCAL_LOGGER:
1221 case LoggerConfig::NOT_LOGGED:
1222 // There is no timestamp channel associated with this, so ignore it.
1223 break;
1224
1225 case LoggerConfig::REMOTE_LOGGER:
1226 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1227 // We want to make a split timestamp channel regardless of what type
1228 // of log this used to be. No sense propagating the single
1229 // timestamp channel.
1230
1231 CHECK(connection->has_timestamp_logger_nodes());
1232 for (const flatbuffers::String *timestamp_logger_node :
1233 *connection->timestamp_logger_nodes()) {
1234 const Node *node = configuration::GetNode(
1235 logged_configuration(), timestamp_logger_node->string_view());
1236 message_bridge::ChannelTimestampFinder finder(
1237 logged_configuration(), "log_reader", node);
1238
1239 // We are assuming here that all the maps are setup correctly to
1240 // handle arbitrary timestamps. Apply the maps for this node to
1241 // see what name this ends up with.
1242 std::string name = finder.SplitChannelName(
1243 pair.second.remapped_name, c->type()->str(), connection);
1244 std::string unmapped_name = name;
1245 configuration::HandleMaps(logged_configuration()->maps(), &name,
1246 "aos.message_bridge.RemoteMessage",
1247 node);
1248 CHECK_NE(name, unmapped_name)
1249 << ": Remote timestamp channel was not remapped, this is "
1250 "very fishy";
1251 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1252 fbb.CreateString(name);
1253 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1254 fbb.CreateString("aos.message_bridge.RemoteMessage");
1255 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1256 fbb.CreateString(timestamp_logger_node->string_view());
1257
1258 // Now, build a channel. Don't log it, 2 senders, and match the
1259 // source frequency.
1260 Channel::Builder channel_builder(fbb);
1261 channel_builder.add_name(channel_name_offset);
1262 channel_builder.add_type(channel_type_offset);
1263 channel_builder.add_source_node(source_node_offset);
1264 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1265 channel_builder.add_num_senders(2);
1266 if (c->has_frequency()) {
1267 channel_builder.add_frequency(c->frequency());
1268 }
1269 channel_offsets.emplace_back(channel_builder.Finish());
1270 }
1271 break;
1272 }
1273 }
1274 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001275 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001276
Austin Schuh0de30f32020-12-06 12:44:28 -08001277 // Now reconstruct the original channels, translating types as needed
1278 for (const Channel *c : *base_config->channels()) {
1279 // Search for a mapping channel.
1280 std::string_view new_type = "";
1281 for (auto &pair : remapped_channels_) {
1282 const Channel *const remapped_channel =
1283 logged_configuration()->channels()->Get(pair.first);
1284 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1285 remapped_channel->type()->string_view() == c->type()->string_view()) {
1286 new_type = pair.second.new_type;
1287 break;
1288 }
1289 }
1290
1291 // Copy everything over.
1292 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1293
1294 // Add the schema if it doesn't exist.
1295 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1296 CHECK(c->has_schema());
1297 schema_map.insert(std::make_pair(c->type()->string_view(),
1298 RecursiveCopyFlatBuffer(c->schema())));
1299 }
1300 }
1301
1302 // The MergeConfiguration API takes a vector, not a map. Convert.
1303 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1304 while (!schema_map.empty()) {
1305 schemas.emplace_back(std::move(schema_map.begin()->second));
1306 schema_map.erase(schema_map.begin());
1307 }
1308
1309 // Create the Configuration containing the new channels that we want to add.
1310 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1311 channels_offset =
1312 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1313
1314 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001315 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001316 if (base_config->maps()) {
1317 for (const Map *map : *base_config->maps()) {
1318 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1319 }
1320 }
1321
1322 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001323 for (const MapT &map : maps_) {
1324 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001325 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001326 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001327 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001328 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001329 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001330 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1331 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001332 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001333 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001334 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001335 match_builder.add_name(match_name_offset);
1336 match_builder.add_type(match_type_offset);
1337 if (!map.match->source_node.empty()) {
1338 match_builder.add_source_node(match_source_node_offset);
1339 }
1340 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1341
Austin Schuh0de30f32020-12-06 12:44:28 -08001342 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001343 rename_builder.add_name(rename_name_offset);
1344 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1345
Austin Schuh0de30f32020-12-06 12:44:28 -08001346 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001347 map_builder.add_match(match_offset);
1348 map_builder.add_rename(rename_offset);
1349 map_offsets.emplace_back(map_builder.Finish());
1350 }
1351
Austin Schuh0de30f32020-12-06 12:44:28 -08001352 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1353 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001354
Austin Schuh0de30f32020-12-06 12:44:28 -08001355 // And copy everything else over.
1356 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1357 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1358
1359 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1360 applications_offset =
1361 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1362
1363 // Now insert everything else in unmodified.
1364 ConfigurationBuilder configuration_builder(fbb);
1365 if (!channels_offset.IsNull()) {
1366 configuration_builder.add_channels(channels_offset);
1367 }
1368 if (!maps_offsets.IsNull()) {
1369 configuration_builder.add_maps(maps_offsets);
1370 }
1371 if (!nodes_offset.IsNull()) {
1372 configuration_builder.add_nodes(nodes_offset);
1373 }
1374 if (!applications_offset.IsNull()) {
1375 configuration_builder.add_applications(applications_offset);
1376 }
1377
1378 if (base_config->has_channel_storage_duration()) {
1379 configuration_builder.add_channel_storage_duration(
1380 base_config->channel_storage_duration());
1381 }
1382
1383 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1384 << ": Merging logic needs to be updated when the number of configuration "
1385 "fields changes.";
1386
1387 fbb.Finish(configuration_builder.Finish());
1388
1389 // Clean it up and return it! By using MergeConfiguration here, we'll
1390 // actually get a deduplicated config for free too.
1391 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1392 configuration::MergeConfiguration(
1393 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1394
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001395 remapped_configuration_buffer_ =
1396 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001397 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001398
1399 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001400
1401 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001402}
1403
Austin Schuh1c227352021-09-17 12:53:54 -07001404std::vector<const Channel *> LogReader::RemappedChannels() const {
1405 std::vector<const Channel *> result;
1406 result.reserve(remapped_channels_.size());
1407 for (auto &pair : remapped_channels_) {
1408 const Channel *const logged_channel =
1409 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1410
1411 auto channel_iterator = std::lower_bound(
1412 remapped_configuration_->channels()->cbegin(),
1413 remapped_configuration_->channels()->cend(),
1414 std::make_pair(std::string_view(pair.second.remapped_name),
1415 logged_channel->type()->string_view()),
1416 CompareChannels);
1417
1418 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1419 CHECK(EqualsChannels(
1420 *channel_iterator,
1421 std::make_pair(std::string_view(pair.second.remapped_name),
1422 logged_channel->type()->string_view())));
1423 result.push_back(*channel_iterator);
1424 }
1425 return result;
1426}
1427
Austin Schuh6f3babe2020-01-26 20:34:50 -08001428const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001429 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001430 const Channel *channel) {
1431 std::string_view channel_name = channel->name()->string_view();
1432 std::string_view channel_type = channel->type()->string_view();
1433 const int channel_index =
1434 configuration::ChannelIndex(logged_configuration(), channel);
1435 // If the channel is remapped, find the correct channel name to use.
1436 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001437 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001438 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001439 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001440 }
1441
Austin Schuhee711052020-08-24 16:06:09 -07001442 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001443 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001444 configuration(), channel_name, channel_type,
1445 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001446
1447 CHECK(remapped_channel != nullptr)
1448 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1449 << channel_type << "\"} because it is not in the provided configuration.";
1450
1451 return remapped_channel;
1452}
1453
Austin Schuh58646e22021-08-23 23:51:46 -07001454LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper,
1455 const Node *node)
1456 : timestamp_mapper_(std::move(timestamp_mapper)), node_(node) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001457
1458void LogReader::State::AddPeer(State *peer) {
1459 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1460 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1461 }
1462}
Austin Schuh858c9f32020-08-31 16:56:12 -07001463
Austin Schuh58646e22021-08-23 23:51:46 -07001464void LogReader::State::SetNodeEventLoopFactory(
Austin Schuhe33c08d2022-02-03 18:15:21 -08001465 NodeEventLoopFactory *node_event_loop_factory,
1466 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001467 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001468 event_loop_factory_ = event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001469}
1470
1471void LogReader::State::SetChannelCount(size_t count) {
1472 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001473 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001474 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001475 channel_source_state_.resize(count);
1476 factory_channel_index_.resize(count);
1477 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001478}
1479
Austin Schuh58646e22021-08-23 23:51:46 -07001480void LogReader::State::SetRemoteTimestampSender(
1481 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1482 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1483}
1484
Austin Schuh858c9f32020-08-31 16:56:12 -07001485void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001486 size_t logged_channel_index, size_t factory_channel_index,
1487 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001488 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1489 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001490 channels_[logged_channel_index] = std::move(sender);
1491 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001492 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001493
Austin Schuh58646e22021-08-23 23:51:46 -07001494 if (is_forwarded) {
1495 queue_index_map_[logged_channel_index] =
1496 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001497 }
1498
1499 factory_channel_index_[logged_channel_index] = factory_channel_index;
1500}
1501
Austin Schuh287d43d2020-12-04 20:19:33 -08001502bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1503 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001504 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001505 uint32_t remote_queue_index = 0xffffffff;
1506
Austin Schuh287d43d2020-12-04 20:19:33 -08001507 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001508 State *source_state =
1509 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001510 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001511 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001512 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001513
Austin Schuh9942bae2021-01-07 22:06:44 -08001514 struct SentTimestamp {
1515 monotonic_clock::time_point monotonic_event_time;
1516 uint32_t queue_index;
1517 } search;
1518
Austin Schuh58646e22021-08-23 23:51:46 -07001519 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1520 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001521 search.monotonic_event_time =
1522 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001523 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001524
1525 // Find the sent time if available.
1526 auto element = std::lower_bound(
1527 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001528 [](ContiguousSentTimestamp a, SentTimestamp b) {
1529 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001530 return true;
1531 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001532 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001533 return false;
1534 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001535
1536 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001537 return true;
1538 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001539 if (a.starting_queue_index >= b.queue_index) {
1540 return false;
1541 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001542
Austin Schuh9942bae2021-01-07 22:06:44 -08001543 // If it isn't clearly below or above, it is below. Since we return
1544 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001545 return false;
1546 });
1547
1548 // TODO(austin): Be a bit more principled here, but we will want to do that
1549 // after the logger rewrite. We hit this when one node finishes, but the
1550 // other node isn't done yet. So there is no send time, but there is a
1551 // receive time.
1552 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001553 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1554 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001555
1556 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001557 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001558 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001559 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001560 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001561 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001562 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001563 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001564
Austin Schuh58646e22021-08-23 23:51:46 -07001565 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001566 element->actual_queue_index -
1567 element->starting_queue_index;
1568 } else {
1569 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001570 }
Austin Schuh58646e22021-08-23 23:51:46 -07001571 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1572 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001573 }
1574
1575 // Send! Use the replayed queue index here instead of the logged queue index
1576 // for the remote queue index. This makes re-logging work.
milind1f1dca32021-07-03 13:50:07 -07001577 const auto err = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001578 RawSender::SharedSpan(timestamped_message.data,
1579 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001580 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001581 timestamped_message.realtime_remote_time, remote_queue_index,
1582 (channel_source_state_[timestamped_message.channel_index] != nullptr
1583 ? CHECK_NOTNULL(
1584 channel_source_state_[timestamped_message.channel_index])
1585 ->event_loop_->boot_uuid()
1586 : event_loop_->boot_uuid()));
milind1f1dca32021-07-03 13:50:07 -07001587 if (err != RawSender::Error::kOk) return false;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001588
Austin Schuh287d43d2020-12-04 20:19:33 -08001589 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001590 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001591 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1592 // Nothing here, start a range with 0 length.
1593 ContiguousSentTimestamp timestamp;
1594 timestamp.starting_monotonic_event_time =
1595 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001596 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001597 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001598 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001599 timestamp.actual_queue_index = sender->sent_queue_index();
1600 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1601 timestamp);
1602 } else {
1603 // We've got something. See if the next timestamp is still contiguous. If
1604 // so, grow it.
1605 ContiguousSentTimestamp *back =
1606 &queue_index_map_[timestamped_message.channel_index]->back();
1607 if ((back->starting_queue_index - back->actual_queue_index) ==
milind1f1dca32021-07-03 13:50:07 -07001608 (timestamped_message.queue_index.index -
1609 sender->sent_queue_index())) {
Austin Schuh58646e22021-08-23 23:51:46 -07001610 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001611 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001612 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001613 } else {
1614 // Otherwise, make a new one.
1615 ContiguousSentTimestamp timestamp;
1616 timestamp.starting_monotonic_event_time =
1617 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001618 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001619 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001620 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001621 timestamp.actual_queue_index = sender->sent_queue_index();
1622 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1623 timestamp);
1624 }
1625 }
1626
1627 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1628 // queue index diverge a couple of elements, which would be a very small
1629 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001630 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1631 nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001632 State *source_state =
1633 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1634
Austin Schuh969cd602021-01-03 00:09:45 -08001635 flatbuffers::FlatBufferBuilder fbb;
1636 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001637 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1638 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001639
Austin Schuh969cd602021-01-03 00:09:45 -08001640 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001641
1642 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001643 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001644
1645 // Swap the remote and sent metrics. They are from the sender's
1646 // perspective, not the receiver's perspective.
1647 message_header_builder.add_monotonic_sent_time(
1648 sender->monotonic_sent_time().time_since_epoch().count());
1649 message_header_builder.add_realtime_sent_time(
1650 sender->realtime_sent_time().time_since_epoch().count());
1651 message_header_builder.add_queue_index(sender->sent_queue_index());
1652
Austin Schuh58646e22021-08-23 23:51:46 -07001653 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1654 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001655 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001656 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1657 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001658 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001659 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001660
1661 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001662 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001663
Austin Schuh969cd602021-01-03 00:09:45 -08001664 fbb.Finish(message_header_builder.Finish());
1665
1666 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1667 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001668 timestamped_message.monotonic_timestamp_time,
1669 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001670 }
1671
1672 return true;
1673}
1674
Austin Schuh969cd602021-01-03 00:09:45 -08001675LogReader::RemoteMessageSender::RemoteMessageSender(
1676 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1677 : event_loop_(event_loop),
1678 sender_(std::move(sender)),
1679 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1680
1681void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1682 if (remote_timestamps_.empty()) {
1683 CHECK_NOTNULL(timer_);
1684 timer_->Disable();
1685 scheduled_time_ = monotonic_clock::min_time;
1686 return;
1687 }
1688
1689 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1690 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001691 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001692 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001693 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1694 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001695 }
1696}
1697
1698void LogReader::RemoteMessageSender::Send(
1699 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001700 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001701 // There are 2 variants of logs.
1702 // 1) Logs without monotonic_timestamp_time
1703 // 2) Logs with monotonic_timestamp_time
1704 //
1705 // As of Jan 2021, we shouldn't have any more logs without
1706 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1707 // the effort of saving.
1708 //
1709 // This gives us 3 cases, 2 of which are undistinguishable.
1710 // 1) Old log without monotonic_timestamp_time.
1711 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1712 // remotely so we actually have monotonic_timestamp_time.
1713 // 3) New log, but the timestamp was logged on the node receiving the message
1714 // so there is no monotonic_timestamp_time.
1715 //
1716 // Our goal when replaying is to accurately reproduce the state of the world
1717 // present when logging. If a timestamp wasn't sent back across the network,
1718 // we shouldn't replay one back across the network.
1719 //
1720 // Given that we don't really care about 1, we can use the presence of the
1721 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1722 // monotonic_timestamp_time, this means the message was logged locally and
1723 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001724 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001725 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001726 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001727
Austin Schuh58646e22021-08-23 23:51:46 -07001728 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
1729
Austin Schuhc41d6a82021-07-16 14:49:23 -07001730 remote_timestamps_.emplace(
1731 std::upper_bound(
1732 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07001733 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07001734 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1735 const Timestamp &timestamp) {
1736 return monotonic_timestamp_time <
1737 timestamp.monotonic_timestamp_time;
1738 }),
Austin Schuh58646e22021-08-23 23:51:46 -07001739 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07001740 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001741}
1742
1743void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001744 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1745 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001746 CHECK(!remote_timestamps_.empty());
1747
1748 // Send out all timestamps at the currently scheduled time.
1749 while (remote_timestamps_.front().monotonic_timestamp_time ==
1750 scheduled_time_) {
milind1f1dca32021-07-03 13:50:07 -07001751 CHECK_EQ(sender_.Send(std::move(remote_timestamps_.front().remote_message)),
1752 RawSender::Error::kOk);
Austin Schuh969cd602021-01-03 00:09:45 -08001753 remote_timestamps_.pop_front();
1754 if (remote_timestamps_.empty()) {
1755 break;
1756 }
1757 }
1758 scheduled_time_ = monotonic_clock::min_time;
1759
1760 ScheduleTimestamp();
1761}
1762
1763LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001764 const Channel *channel, const Connection *connection) {
1765 message_bridge::ChannelTimestampFinder finder(event_loop_);
1766 // Look at any pre-created channel/connection pairs.
1767 {
1768 auto it =
1769 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1770 if (it != channel_timestamp_loggers_.end()) {
1771 return it->second.get();
1772 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001773 }
1774
Austin Schuh61e973f2021-02-21 21:43:56 -08001775 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1776 // to.
1777 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1778
1779 {
1780 // See if that has been created before. If so, cache it in
1781 // channel_timestamp_loggers_ and return.
1782 auto it = timestamp_loggers_.find(timestamp_channel);
1783 if (it != timestamp_loggers_.end()) {
1784 CHECK(channel_timestamp_loggers_
1785 .try_emplace(std::make_pair(channel, connection), it->second)
1786 .second);
1787 return it->second.get();
1788 }
1789 }
1790
1791 // Otherwise, make a sender, save it, and cache it.
1792 auto result = channel_timestamp_loggers_.try_emplace(
1793 std::make_pair(channel, connection),
1794 std::make_shared<RemoteMessageSender>(
1795 event_loop()->MakeSender<RemoteMessage>(
1796 timestamp_channel->name()->string_view()),
1797 event_loop()));
1798
1799 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1800 .second);
1801 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001802}
1803
Austin Schuhdda74ec2021-01-03 19:30:37 -08001804TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001805 CHECK(timestamp_mapper_ != nullptr);
1806 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1807 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001808
Austin Schuhe639ea12021-01-25 13:00:22 -08001809 TimestampedMessage result = std::move(*result_ptr);
1810
Austin Schuh2f8fd752020-09-01 22:38:28 -07001811 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001812 << result.monotonic_event_time;
1813 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001814 SeedSortedMessages();
1815
Austin Schuh58646e22021-08-23 23:51:46 -07001816 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001817
Austin Schuh5ee56872021-01-30 16:53:34 -08001818 VLOG(1) << "Popped " << result
1819 << configuration::CleanedChannelToString(
1820 event_loop_->configuration()->channels()->Get(
1821 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001822 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001823}
1824
Austin Schuhe33c08d2022-02-03 18:15:21 -08001825BootTimestamp LogReader::State::OldestMessageTime() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001826 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001827 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08001828 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001829 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1830 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001831 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08001832 }
Austin Schuh0b8a5502021-11-18 15:34:12 -08001833 VLOG(2) << MaybeNodeName(node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001834 << result_ptr->monotonic_event_time.time;
Austin Schuhe33c08d2022-02-03 18:15:21 -08001835
1836 if (result_ptr->monotonic_event_time.boot == boot_count()) {
1837 ObserveNextMessage(result_ptr->monotonic_event_time.time,
1838 result_ptr->realtime_event_time);
1839 }
1840
Austin Schuh58646e22021-08-23 23:51:46 -07001841 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001842}
1843
1844void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001845 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001846
Austin Schuhe639ea12021-01-25 13:00:22 -08001847 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1848 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001849}
1850
1851void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07001852 if (started_ && !stopped_) {
Austin Schuhe33c08d2022-02-03 18:15:21 -08001853 NotifyLogfileEnd();
Austin Schuh58646e22021-08-23 23:51:46 -07001854 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001855 for (size_t i = 0; i < channels_.size(); ++i) {
1856 channels_[i].reset();
1857 }
Austin Schuhe33c08d2022-02-03 18:15:21 -08001858 ClearTimeFlags();
Austin Schuh61e973f2021-02-21 21:43:56 -08001859 channel_timestamp_loggers_.clear();
1860 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001861 event_loop_unique_ptr_.reset();
1862 event_loop_ = nullptr;
1863 timer_handler_ = nullptr;
1864 node_event_loop_factory_ = nullptr;
1865}
1866
Austin Schuhe33c08d2022-02-03 18:15:21 -08001867void LogReader::State::SetStartTimeFlag(realtime_clock::time_point start_time) {
1868 if (start_time != realtime_clock::min_time) {
1869 start_event_notifier_ = std::make_unique<EventNotifier>(
1870 event_loop_, [this]() { NotifyFlagStart(); }, "flag_start", start_time);
1871 }
1872}
1873
1874void LogReader::State::SetEndTimeFlag(realtime_clock::time_point end_time) {
1875 if (end_time != realtime_clock::max_time) {
1876 end_event_notifier_ = std::make_unique<EventNotifier>(
1877 event_loop_, [this]() { NotifyFlagEnd(); }, "flag_end", end_time);
1878 }
1879}
1880
1881void LogReader::State::ObserveNextMessage(
1882 monotonic_clock::time_point monotonic_event,
1883 realtime_clock::time_point realtime_event) {
1884 if (start_event_notifier_) {
1885 start_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
1886 }
1887 if (end_event_notifier_) {
1888 end_event_notifier_->ObserveNextMessage(monotonic_event, realtime_event);
1889 }
1890}
1891
1892void LogReader::State::ClearTimeFlags() {
1893 start_event_notifier_.reset();
1894 end_event_notifier_.reset();
1895}
1896
1897void LogReader::State::NotifyLogfileStart() {
1898 if (start_event_notifier_) {
1899 if (start_event_notifier_->realtime_event_time() >
1900 realtime_start_time(boot_count())) {
1901 VLOG(1) << "Skipping, " << start_event_notifier_->realtime_event_time()
1902 << " > " << realtime_start_time(boot_count());
1903 return;
1904 }
1905 }
1906 if (found_last_message_) {
1907 VLOG(1) << "Last message already found, bailing";
1908 return;
1909 }
1910 RunOnStart();
1911}
1912
1913void LogReader::State::NotifyFlagStart() {
1914 if (start_event_notifier_->realtime_event_time() >=
1915 realtime_start_time(boot_count())) {
1916 RunOnStart();
1917 }
1918}
1919
1920void LogReader::State::NotifyLogfileEnd() {
1921 if (found_last_message_) {
1922 return;
1923 }
1924
1925 if (!stopped_ && started_) {
1926 RunOnEnd();
1927 }
1928}
1929
1930void LogReader::State::NotifyFlagEnd() {
1931 if (!stopped_ && started_) {
1932 RunOnEnd();
1933 SetFoundLastMessage(true);
1934 }
1935}
1936
Austin Schuhe309d2a2019-11-29 13:25:21 -08001937} // namespace logger
1938} // namespace aos