blob: efcb40a864f6ef4c60ce1950bd69f61ebed48a70 [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>
Austin Schuh4c4e0092019-12-22 16:18:03 -08004#include <limits.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08008
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 Schuhe309d2a2019-11-29 13:25:21 -080042namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070043namespace configuration {
44// We don't really want to expose this publicly, but log reader doesn't really
45// want to re-implement it.
46void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
47 std::string *name, std::string_view type, const Node *node);
48}
Austin Schuhe309d2a2019-11-29 13:25:21 -080049namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070050namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080051
Austin Schuh315b96b2020-12-11 21:21:12 -080052std::string LogFileVectorToString(std::vector<LogFile> log_files) {
53 std::stringstream ss;
Austin Schuh297d2352021-01-21 19:02:17 -080054 for (const auto &f : log_files) {
Austin Schuh315b96b2020-12-11 21:21:12 -080055 ss << f << "\n";
56 }
57 return ss.str();
58}
59
Austin Schuh0de30f32020-12-06 12:44:28 -080060// Copies the channel, removing the schema as we go. If new_name is provided,
61// it is used instead of the name inside the channel. If new_type is provided,
62// it is used instead of the type in the channel.
63flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
64 std::string_view new_name,
65 std::string_view new_type,
66 flatbuffers::FlatBufferBuilder *fbb) {
67 flatbuffers::Offset<flatbuffers::String> name_offset =
68 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
69 : new_name);
70 flatbuffers::Offset<flatbuffers::String> type_offset =
71 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
72 flatbuffers::Offset<flatbuffers::String> source_node_offset =
73 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
74 : 0;
75
76 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
77 destination_nodes_offset =
78 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
79
80 flatbuffers::Offset<
81 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
82 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
83
84 Channel::Builder channel_builder(*fbb);
85 channel_builder.add_name(name_offset);
86 channel_builder.add_type(type_offset);
87 if (c->has_frequency()) {
88 channel_builder.add_frequency(c->frequency());
89 }
90 if (c->has_max_size()) {
91 channel_builder.add_max_size(c->max_size());
92 }
93 if (c->has_num_senders()) {
94 channel_builder.add_num_senders(c->num_senders());
95 }
96 if (c->has_num_watchers()) {
97 channel_builder.add_num_watchers(c->num_watchers());
98 }
99 if (!source_node_offset.IsNull()) {
100 channel_builder.add_source_node(source_node_offset);
101 }
102 if (!destination_nodes_offset.IsNull()) {
103 channel_builder.add_destination_nodes(destination_nodes_offset);
104 }
105 if (c->has_logger()) {
106 channel_builder.add_logger(c->logger());
107 }
108 if (!logger_nodes_offset.IsNull()) {
109 channel_builder.add_logger_nodes(logger_nodes_offset);
110 }
111 if (c->has_read_method()) {
112 channel_builder.add_read_method(c->read_method());
113 }
114 if (c->has_num_readers()) {
115 channel_builder.add_num_readers(c->num_readers());
116 }
117 return channel_builder.Finish();
118}
119
Austin Schuhe309d2a2019-11-29 13:25:21 -0800120namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800121using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700122} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800123
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800124LogReader::LogReader(std::string_view filename,
125 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800126 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800127
Austin Schuh287d43d2020-12-04 20:19:33 -0800128LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800129 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800130 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800131 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800132 CHECK_GT(log_files_.size(), 0u);
133 {
134 // Validate that we have the same config everwhere. This will be true if
135 // all the parts were sorted together and the configs match.
136 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800137 for (const LogFile &log_file : log_files_) {
138 if (log_file.config.get() == nullptr) {
139 LOG(FATAL) << "Couldn't find a config in " << log_file;
140 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800141 if (config == nullptr) {
142 config = log_file.config.get();
143 } else {
144 CHECK_EQ(config, log_file.config.get());
145 }
146 }
147 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800148
Austin Schuh6331ef92020-01-07 18:28:09 -0800149 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800150
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700151 // Remap all existing remote timestamp channels. They will be recreated, and
152 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700153 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800154 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
155 "log_reader", node);
156
157 absl::btree_set<std::string_view> remote_nodes;
158
159 for (const Channel *channel : *logged_configuration()->channels()) {
160 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
161 continue;
162 }
163 if (!channel->has_destination_nodes()) {
164 continue;
165 }
166 for (const Connection *connection : *channel->destination_nodes()) {
167 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
168 node)) {
169 // Start by seeing if the split timestamp channels are being used for
170 // this message. If so, remap them.
171 const Channel *timestamp_channel = configuration::GetChannel(
172 logged_configuration(),
173 finder.SplitChannelName(channel, connection),
174 RemoteMessage::GetFullyQualifiedName(), "", node, true);
175
176 if (timestamp_channel != nullptr) {
177 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
178 RemapLoggedChannel<RemoteMessage>(
179 timestamp_channel->name()->string_view(), node);
180 }
181 continue;
182 }
183
184 // Otherwise collect this one up as a node to look for a combined
185 // channel from. It is more efficient to compare nodes than channels.
186 remote_nodes.insert(connection->name()->string_view());
187 }
188 }
189 }
190
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700191 std::vector<const Node *> timestamp_logger_nodes =
192 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800193 for (const std::string_view remote_node : remote_nodes) {
194 const std::string channel = finder.CombinedChannelName(remote_node);
195
Austin Schuh0de30f32020-12-06 12:44:28 -0800196 // See if the log file is an old log with MessageHeader channels in it, or
197 // a newer log with RemoteMessage. If we find an older log, rename the
198 // type too along with the name.
199 if (HasChannel<MessageHeader>(channel, node)) {
200 CHECK(!HasChannel<RemoteMessage>(channel, node))
201 << ": Can't have both a MessageHeader and RemoteMessage remote "
202 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800203 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
204 // careful about updating the config, but there are fewer and fewer logs
205 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800206 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
207 "aos.message_bridge.RemoteMessage");
208 } else {
209 CHECK(HasChannel<RemoteMessage>(channel, node))
210 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
211 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
212 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800213 // Only bother to remap if there's something on the channel. We can
214 // tell if the channel was marked NOT_LOGGED or not. This makes the
215 // config not change un-necesarily when we replay a log with NOT_LOGGED
216 // messages.
217 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
218 RemapLoggedChannel<RemoteMessage>(channel, node);
219 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800220 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700221 }
222 }
223
Austin Schuh6aa77be2020-02-22 21:06:40 -0800224 if (replay_configuration) {
225 CHECK_EQ(configuration::MultiNode(configuration()),
226 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700227 << ": Log file and replay config need to both be multi or single "
228 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800229 }
230
Austin Schuh6f3babe2020-01-26 20:34:50 -0800231 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800232 states_.emplace_back(std::make_unique<State>(
233 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800234 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800235 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700236 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800237 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700238 << ": Log file and replay config need to have matching nodes "
239 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700240 for (const Node *node : *logged_configuration()->nodes()) {
241 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700242 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
243 << " in logged config that is not present in the replay "
244 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700245 }
246 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800247 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800248 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800249 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800250}
251
Austin Schuh6aa77be2020-02-22 21:06:40 -0800252LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700253 if (event_loop_factory_unique_ptr_) {
254 Deregister();
255 } else if (event_loop_factory_ != nullptr) {
256 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
257 "is destroyed";
258 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700259 // Zero out some buffers. It's easy to do use-after-frees on these, so make
260 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700261 if (remapped_configuration_buffer_) {
262 remapped_configuration_buffer_->Wipe();
263 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800264}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800265
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800266const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800267 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800268}
269
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800270const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800271 return remapped_configuration_;
272}
273
Austin Schuh07676622021-01-21 18:59:17 -0800274std::vector<const Node *> LogReader::LoggedNodes() const {
275 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800276}
Austin Schuh15649d62019-12-28 16:36:38 -0800277
Austin Schuh11d43732020-09-21 17:28:30 -0700278monotonic_clock::time_point LogReader::monotonic_start_time(
279 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800280 State *state =
281 states_[configuration::GetNodeIndex(configuration(), node)].get();
282 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
283
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700284 // TODO(austin): Un-hard-code the 0 boot count.
285 return state->monotonic_start_time(0);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800286}
287
Austin Schuh11d43732020-09-21 17:28:30 -0700288realtime_clock::time_point LogReader::realtime_start_time(
289 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800290 State *state =
291 states_[configuration::GetNodeIndex(configuration(), node)].get();
292 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
293
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700294 // TODO(austin): Un-hard-code the 0 boot count.
295 return state->realtime_start_time(0);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800296}
297
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800298void LogReader::Register() {
299 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800300 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800301 Register(event_loop_factory_unique_ptr_.get());
302}
303
Austin Schuh92547522019-12-28 14:33:43 -0800304void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800305 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700306 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800307 filters_ =
308 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800309 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuhfe3fb342021-01-16 18:50:37 -0800310 FLAGS_skip_order_validation,
311 chrono::duration_cast<chrono::nanoseconds>(
312 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800313
Austin Schuhe639ea12021-01-25 13:00:22 -0800314 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700315 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800316 const size_t node_index =
317 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800318 std::vector<LogParts> filtered_parts = FilterPartsForNode(
319 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800320
321 // Confirm that all the parts are from the same boot if there are enough
322 // parts to not be from the same boot.
323 if (filtered_parts.size() > 1u) {
324 for (size_t i = 1; i < filtered_parts.size(); ++i) {
325 CHECK_EQ(filtered_parts[i].source_boot_uuid,
326 filtered_parts[0].source_boot_uuid)
Austin Schuh8902fa52021-03-14 22:39:24 -0700327 << ": Found parts from different boots for node "
328 << node->name()->string_view() << " "
Austin Schuh315b96b2020-12-11 21:21:12 -0800329 << LogFileVectorToString(log_files_);
330 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800331 if (!filtered_parts[0].source_boot_uuid.empty()) {
332 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
333 filtered_parts[0].source_boot_uuid);
334 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800335 }
336
Austin Schuh287d43d2020-12-04 20:19:33 -0800337 states_[node_index] = std::make_unique<State>(
338 filtered_parts.size() == 0u
339 ? nullptr
340 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800341 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700342 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700343 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700344
345 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800346 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800347 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800348 filters_->SetTimestampMappers(std::move(timestamp_mappers));
349
350 // Note: this needs to be set before any times are pulled, or we won't observe
351 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800352 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700353
Austin Schuh287d43d2020-12-04 20:19:33 -0800354 for (const Node *node : configuration::GetNodes(configuration())) {
355 const size_t node_index =
356 configuration::GetNodeIndex(configuration(), node);
357 State *state = states_[node_index].get();
358 for (const Node *other_node : configuration::GetNodes(configuration())) {
359 const size_t other_node_index =
360 configuration::GetNodeIndex(configuration(), other_node);
361 State *other_state = states_[other_node_index].get();
362 if (other_state != state) {
363 state->AddPeer(other_state);
364 }
365 }
366 }
367
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700368 // Register after making all the State objects so we can build references
369 // between them.
370 for (const Node *node : configuration::GetNodes(configuration())) {
371 const size_t node_index =
372 configuration::GetNodeIndex(configuration(), node);
373 State *state = states_[node_index].get();
374
375 Register(state->event_loop());
376 }
377
James Kuszmaul46d82582020-05-09 19:50:09 -0700378 if (live_nodes_ == 0) {
379 LOG(FATAL)
380 << "Don't have logs from any of the nodes in the replay config--are "
381 "you sure that the replay config matches the original config?";
382 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800383
Austin Schuh87dd3832021-01-01 23:07:31 -0800384 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800385
Austin Schuh858c9f32020-08-31 16:56:12 -0700386 for (std::unique_ptr<State> &state : states_) {
387 state->SeedSortedMessages();
388 }
389
Austin Schuh2f8fd752020-09-01 22:38:28 -0700390 // We want to start the log file at the last start time of the log files
391 // from all the nodes. Compute how long each node's simulation needs to run
392 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800393 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800394
Austin Schuh2f8fd752020-09-01 22:38:28 -0700395 // TODO(austin): We want an "OnStart" callback for each node rather than
396 // running until the last node.
397
Austin Schuh8bd96322020-02-13 21:18:22 -0800398 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700399 VLOG(1) << "Start time is " << state->monotonic_start_time(0) << " for node "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700400 << MaybeNodeName(state->event_loop()->node()) << "now "
401 << state->monotonic_now();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700402 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800403 continue;
404 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700405 // And start computing the start time on the distributed clock now that
406 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -0700407 start_time = std::max(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700408 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
Austin Schuhcde938c2020-02-02 17:30:07 -0800409 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700410
Austin Schuh87dd3832021-01-01 23:07:31 -0800411 // TODO(austin): If a node doesn't have a start time, we might not queue
412 // enough. If this happens, we'll explode with a frozen error eventually.
413
Austin Schuh2f8fd752020-09-01 22:38:28 -0700414 CHECK_GE(start_time, distributed_clock::epoch())
415 << ": Hmm, we have a node starting before the start of time. Offset "
416 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -0800417
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418 // Forwarding is tracked per channel. If it is enabled, we want to turn it
419 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700420 // nodes, and also replayed on the other nodes. This may not satisfy all
421 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800422 if (configuration::MultiNode(event_loop_factory_->configuration())) {
423 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
424 const Channel *channel = logged_configuration()->channels()->Get(i);
425 const Node *node = configuration::GetNode(
426 configuration(), channel->source_node()->string_view());
427
Austin Schuh8bd96322020-02-13 21:18:22 -0800428 State *state =
429 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800430
431 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -0700432 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800433
434 event_loop_factory_->DisableForwarding(remapped_channel);
435 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700436
437 // If we are replaying a log, we don't want a bunch of redundant messages
438 // from both the real message bridge and simulated message bridge.
439 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800440 }
441
Austin Schuhcde938c2020-02-02 17:30:07 -0800442 // While we are starting the system up, we might be relying on matching data
443 // to timestamps on log files where the timestamp log file starts before the
444 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800445 {
446 const bool prior_ignore_missing_data = ignore_missing_data_;
447 ignore_missing_data_ = true;
448 VLOG(1) << "Running until " << start_time << " in Register";
449 event_loop_factory_->RunFor(start_time.time_since_epoch());
450 VLOG(1) << "At start time";
451 // Now that we are running for real, missing data means that the log file is
452 // corrupted or went wrong.
453 ignore_missing_data_ = prior_ignore_missing_data;
454 }
Austin Schuh92547522019-12-28 14:33:43 -0800455
Austin Schuh8bd96322020-02-13 21:18:22 -0800456 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700457 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700458 if (state->realtime_start_time(0) != realtime_clock::min_time) {
459 state->SetRealtimeOffset(state->monotonic_start_time(0),
460 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700461 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700462 VLOG(1) << "Start time is " << state->monotonic_start_time(0) << " for node "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463 << MaybeNodeName(state->event_loop()->node()) << "now "
464 << state->monotonic_now();
465 }
466
467 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800468 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800469 }
470}
471
Austin Schuh2f8fd752020-09-01 22:38:28 -0700472message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800473 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800474 if (filters_) {
475 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800476 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800477 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800478}
479
Austin Schuhe309d2a2019-11-29 13:25:21 -0800480void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800481 State *state =
482 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
483 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800484
Austin Schuh858c9f32020-08-31 16:56:12 -0700485 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800486
Tyler Chatow67ddb032020-01-12 14:30:04 -0800487 // We don't run timing reports when trying to print out logged data, because
488 // otherwise we would end up printing out the timing reports themselves...
489 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800490 event_loop->SkipTimingReport();
491 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -0800492
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700493 for (size_t logged_channel_index = 0;
494 logged_channel_index < logged_configuration()->channels()->size();
495 ++logged_channel_index) {
496 const Channel *channel = RemapChannel(
497 event_loop,
498 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800499
Austin Schuh532656d2021-01-11 10:17:18 -0800500 if (channel->logger() == LoggerConfig::NOT_LOGGED) {
501 continue;
502 }
503
Austin Schuh2f8fd752020-09-01 22:38:28 -0700504 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -0800505 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700506
507 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800508
509 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
510 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700511 // We've got a message which is being forwarded to this node.
512 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -0800513 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700514 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800515
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700516 // Delivery timestamps are supposed to be logged back on the source node.
517 // Configure remote timestamps to be sent.
Austin Schuh61e973f2021-02-21 21:43:56 -0800518 const Connection *connection =
519 configuration::ConnectionToNode(channel, event_loop->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700520 const bool delivery_time_is_logged =
Austin Schuh61e973f2021-02-21 21:43:56 -0800521 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
522 source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700523
524 source_state =
525 states_[configuration::GetNodeIndex(configuration(), source_node)]
526 .get();
527
528 if (delivery_time_is_logged) {
529 remote_timestamp_sender =
Austin Schuh61e973f2021-02-21 21:43:56 -0800530 source_state->RemoteTimestampSender(channel, connection);
Austin Schuh8bd96322020-02-13 21:18:22 -0800531 }
532 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700533
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700534 state->SetChannel(
535 logged_channel_index,
536 configuration::ChannelIndex(event_loop->configuration(), channel),
537 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
538 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800539 }
540
Austin Schuh6aa77be2020-02-22 21:06:40 -0800541 // If we didn't find any log files with data in them, we won't ever get a
542 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -0800543 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800544 return;
545 }
546
Austin Schuh858c9f32020-08-31 16:56:12 -0700547 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700548 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
549 << "at " << state->event_loop()->context().monotonic_event_time
550 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700551 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800552 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700553 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800554 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800555 event_loop_factory_->Exit();
556 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800557 return;
558 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700559
Austin Schuhdda74ec2021-01-03 19:30:37 -0800560 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700561 CHECK_EQ(timestamped_message.monotonic_event_time.boot, 0u);
562 CHECK_EQ(timestamped_message.monotonic_remote_time.boot, 0u);
563 CHECK_EQ(timestamped_message.monotonic_timestamp_time.boot, 0u);
Austin Schuh05b70472020-01-01 17:11:17 -0800564
Austin Schuhe309d2a2019-11-29 13:25:21 -0800565 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700566 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700567 if (!FLAGS_skip_order_validation) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700568 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700569 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
570 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800571 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700572 << state->DebugString();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700573 } else if (BootTimestamp{.boot = 0u, .time = monotonic_now} !=
574 timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700575 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800576 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700577 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800578 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700579 << "): " << FlatbufferToJson(state->event_loop()->node())
580 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800581 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700582 << state->DebugString();
583 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800584
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700585 if (timestamped_message.monotonic_event_time.time >
586 state->monotonic_start_time(
587 timestamped_message.monotonic_event_time.boot) ||
Austin Schuh15649d62019-12-28 16:36:38 -0800588 event_loop_factory_ != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800589 if (timestamped_message.data.span().size() != 0u) {
590 if (timestamped_message.monotonic_remote_time !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700591 BootTimestamp::min_time()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800592 // Confirm that the message was sent on the sending node before the
593 // destination node (this node). As a proxy, do this by making sure
594 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800595 //
596 // TODO(austin): <= means that the cause message (which we know) could
597 // happen after the effect even though we know they are at the same
598 // time. I doubt anyone will notice for a bit, but we should really
599 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700600 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800601 CHECK_LE(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700602 timestamped_message.monotonic_remote_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800603 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700604 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800605 << state->remote_node(timestamped_message.channel_index)
606 ->name()
607 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800608 << " while trying to send a message on "
609 << configuration::CleanedChannelToString(
610 logged_configuration()->channels()->Get(
611 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700612 << " " << state->DebugString();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700613 } else if (timestamped_message.monotonic_remote_time.time >
Austin Schuh287d43d2020-12-04 20:19:33 -0800614 state->monotonic_remote_now(
615 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700616 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800617 << "Check failed: timestamped_message.monotonic_remote_time < "
618 "state->monotonic_remote_now(timestamped_message.channel_"
619 "index) ("
620 << timestamped_message.monotonic_remote_time << " vs. "
621 << state->monotonic_remote_now(
622 timestamped_message.channel_index)
623 << ") " << state->event_loop()->node()->name()->string_view()
624 << " to "
625 << state->remote_node(timestamped_message.channel_index)
626 ->name()
627 ->string_view()
628 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700629 << " ("
630 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700631 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700632 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800633 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700634 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800635 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700636 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700637 << ") " << state->DebugString();
638 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800639 }
640
Austin Schuh15649d62019-12-28 16:36:38 -0800641 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700642 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800643 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800644
Austin Schuh2f8fd752020-09-01 22:38:28 -0700645 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800646 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700647 // TODO(austin): std::move channel_data in and make that efficient in
648 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800649 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800650 } else if (!ignore_missing_data_ &&
Austin Schuh5ee56872021-01-30 16:53:34 -0800651 // When starting up, we can have data which was sent before the
652 // log starts, but the timestamp was after the log starts. This
653 // is unreasonable to avoid, so ignore the missing data.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700654 timestamped_message.monotonic_remote_time.time >=
Austin Schuh5ee56872021-01-30 16:53:34 -0800655 state->monotonic_remote_start_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700656 timestamped_message.monotonic_remote_time.boot,
Austin Schuh5ee56872021-01-30 16:53:34 -0800657 timestamped_message.channel_index) &&
Austin Schuhdda74ec2021-01-03 19:30:37 -0800658 !FLAGS_skip_missing_forwarding_entries) {
Austin Schuh5ee56872021-01-30 16:53:34 -0800659 // We've found a timestamp without data that we expect to have data for.
660 // This likely means that we are at the end of the log file. Record it
661 // and CHECK that in the rest of the log file, we don't find any more
662 // data on that channel. Not all channels will end at the same point in
663 // time since they can be in different files.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800664 VLOG(1) << "Found the last message on channel "
Austin Schuh94526302021-04-28 22:46:34 -0700665 << timestamped_message.channel_index << ", "
666 << configuration::CleanedChannelToString(
667 logged_configuration()->channels()->Get(
668 timestamped_message.channel_index));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800669
Austin Schuh2bb80e02021-03-20 21:46:17 -0700670 // The user might be working with log files from 1 node but forgot to
671 // configure the infrastructure to log data for a remote channel on that
672 // node. That can be very hard to debug, even though the log reader is
673 // doing the right thing. At least log a warning in that case and tell
674 // the user what is happening so they can either update their config to
675 // log the channel or can find a log with the data.
676 {
677 const std::vector<std::string> logger_nodes =
678 FindLoggerNodes(log_files_);
679 if (logger_nodes.size()) {
680 // We have old logs which don't have the logger nodes logged. In
681 // that case, we can't be helpful :(
682 bool data_logged = false;
683 const Channel *channel = logged_configuration()->channels()->Get(
684 timestamped_message.channel_index);
685 for (const std::string &node : logger_nodes) {
686 data_logged |=
687 configuration::ChannelMessageIsLoggedOnNode(channel, node);
688 }
689 if (!data_logged) {
690 LOG(WARNING) << "Got a timestamp without any logfiles which "
691 "could contain data for channel "
692 << configuration::CleanedChannelToString(channel);
693 LOG(WARNING) << "Only have logs logged on ["
694 << absl::StrJoin(logger_nodes, ", ") << "]";
695 LOG(WARNING)
696 << "Dropping the rest of the data on "
697 << state->event_loop()->node()->name()->string_view();
698 LOG(WARNING)
699 << "Consider using --skip_missing_forwarding_entries to "
700 "bypass this, update your config to log it, or add data "
701 "from one of the nodes it is logged on.";
702 }
703 }
704 }
705
Austin Schuhdda74ec2021-01-03 19:30:37 -0800706 // Vector storing if we've seen a nullptr message or not per channel.
707 std::vector<bool> last_message;
708 last_message.resize(logged_configuration()->channels()->size(), false);
709
710 last_message[timestamped_message.channel_index] = true;
711
712 // Now that we found the end of one channel, artificially stop the
713 // rest. It is confusing when part of your data gets replayed but not
Austin Schuh5ee56872021-01-30 16:53:34 -0800714 // all. Read the rest of the messages and drop them on the floor while
715 // doing some basic validation.
Austin Schuh858c9f32020-08-31 16:56:12 -0700716 while (state->OldestMessageTime() != monotonic_clock::max_time) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800717 TimestampedMessage next = state->PopOldest();
718 // Make sure that once we have seen the last message on a channel,
719 // data doesn't start back up again. If the user wants to play
720 // through events like this, they can set
721 // --skip_missing_forwarding_entries or ignore_missing_data_.
722 CHECK_LT(next.channel_index, last_message.size());
723 if (next.data.span().size() == 0u) {
724 last_message[next.channel_index] = true;
725 } else {
726 if (last_message[next.channel_index]) {
727 LOG(FATAL)
728 << "Found missing data in the middle of the log file on "
729 "channel "
730 << next.channel_index << " Last "
731 << last_message[next.channel_index] << state->DebugString();
732 }
733 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800734 }
Austin Schuh92547522019-12-28 14:33:43 -0800735 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800736 } else {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700737 LOG(WARNING) << "Not sending data from before the start of the log file. "
738 << timestamped_message.monotonic_event_time.time
739 .time_since_epoch()
740 .count()
741 << " start "
742 << monotonic_start_time().time_since_epoch().count() << " "
743 << FlatbufferToJson(
744 timestamped_message.data,
745 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -0800746 }
747
Austin Schuh858c9f32020-08-31 16:56:12 -0700748 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800749 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700750 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
751 << "wakeup for " << next_time << "("
752 << state->ToDistributedClock(next_time)
753 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700754 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -0800755 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700756 VLOG(1) << MaybeNodeName(state->event_loop()->node())
757 << "No next message, scheduling shutdown";
758 // Set a timer up immediately after now to die. If we don't do this,
759 // then the senders waiting on the message we just read will never get
760 // called.
Austin Schuheecb9282020-01-08 17:43:30 -0800761 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700762 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
763 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -0800764 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800765 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800766
Austin Schuh2f8fd752020-09-01 22:38:28 -0700767 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
768 << state->event_loop()->context().monotonic_event_time << " now "
769 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700770 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800771
Austin Schuh6f3babe2020-01-26 20:34:50 -0800772 ++live_nodes_;
773
Austin Schuh858c9f32020-08-31 16:56:12 -0700774 if (state->OldestMessageTime() != monotonic_clock::max_time) {
775 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -0800776 }
777}
778
779void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800780 // Make sure that things get destroyed in the correct order, rather than
781 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -0800782 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700783 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800784 }
Austin Schuh92547522019-12-28 14:33:43 -0800785
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800786 event_loop_factory_unique_ptr_.reset();
787 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800788}
789
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800790void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800791 std::string_view add_prefix,
792 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800793 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
794 const Channel *const channel = logged_configuration()->channels()->Get(ii);
795 if (channel->name()->str() == name &&
796 channel->type()->string_view() == type) {
797 CHECK_EQ(0u, remapped_channels_.count(ii))
798 << "Already remapped channel "
799 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800800 RemappedChannel remapped_channel;
801 remapped_channel.remapped_name =
802 std::string(add_prefix) + std::string(name);
803 remapped_channel.new_type = new_type;
804 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800805 VLOG(1) << "Remapping channel "
806 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -0800807 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -0800808 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800809 return;
810 }
811 }
812 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
813 << type;
814}
815
Austin Schuh01b4c352020-09-21 23:09:39 -0700816void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
817 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800818 std::string_view add_prefix,
819 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -0700820 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
821 const Channel *remapped_channel =
822 configuration::GetChannel(logged_configuration(), name, type, "", node);
823 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
824 << "\", \"type\": \"" << type << "\"}";
825 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
826 << "\"}";
827 VLOG(1) << "Remapped "
828 << aos::configuration::StrippedChannelToString(remapped_channel);
829
830 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
831 // we want it to degrade if the heuristics fail to just work.
832 //
833 // The easiest way to do this is going to be incredibly specific and verbose.
834 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
835 // /original/0/spray. Then, create a map from /original/spray to
836 // /original/0/spray for just the type we were asked for.
837 if (name != remapped_channel->name()->string_view()) {
838 MapT new_map;
839 new_map.match = std::make_unique<ChannelT>();
840 new_map.match->name = absl::StrCat(add_prefix, name);
841 new_map.match->type = type;
842 if (node != nullptr) {
843 new_map.match->source_node = node->name()->str();
844 }
845 new_map.rename = std::make_unique<ChannelT>();
846 new_map.rename->name =
847 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
848 maps_.emplace_back(std::move(new_map));
849 }
850
851 const size_t channel_index =
852 configuration::ChannelIndex(logged_configuration(), remapped_channel);
853 CHECK_EQ(0u, remapped_channels_.count(channel_index))
854 << "Already remapped channel "
855 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800856
857 RemappedChannel remapped_channel_struct;
858 remapped_channel_struct.remapped_name =
859 std::string(add_prefix) +
860 std::string(remapped_channel->name()->string_view());
861 remapped_channel_struct.new_type = new_type;
862 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -0700863 MakeRemappedConfig();
864}
865
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800866void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -0800867 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800868 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700869 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -0800870 << ": Can't change the mapping after the events are scheduled.";
871 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800872 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800873
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800874 // If no remapping occurred and we are using the original config, then there
875 // is nothing interesting to do here.
876 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800877 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800878 return;
879 }
880 // Config to copy Channel definitions from. Use the specified
881 // replay_configuration_ if it has been provided.
882 const Configuration *const base_config = replay_configuration_ == nullptr
883 ? logged_configuration()
884 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800885
886 // Create a config with all the channels, but un-sorted/merged. Collect up
887 // the schemas while we do this. Call MergeConfiguration to sort everything,
888 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800889
890 // This is the builder that we use for the config containing all the new
891 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -0800892 flatbuffers::FlatBufferBuilder fbb;
893 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800894 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -0800895
896 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
897 << ": Merging logic needs to be updated when the number of channel "
898 "fields changes.";
899
900 // List of schemas.
901 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
902 // Make sure our new RemoteMessage schema is in there for old logs without it.
903 schema_map.insert(std::make_pair(
904 RemoteMessage::GetFullyQualifiedName(),
905 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
906 message_bridge::RemoteMessageSchema()))));
907
908 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800909 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -0800910 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800911 base_config, logged_configuration()->channels()->Get(pair.first), "",
912 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -0800913 channel_offsets.emplace_back(
914 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -0700915
916 if (c->has_destination_nodes()) {
917 for (const Connection *connection : *c->destination_nodes()) {
918 switch (connection->timestamp_logger()) {
919 case LoggerConfig::LOCAL_LOGGER:
920 case LoggerConfig::NOT_LOGGED:
921 // There is no timestamp channel associated with this, so ignore it.
922 break;
923
924 case LoggerConfig::REMOTE_LOGGER:
925 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
926 // We want to make a split timestamp channel regardless of what type
927 // of log this used to be. No sense propagating the single
928 // timestamp channel.
929
930 CHECK(connection->has_timestamp_logger_nodes());
931 for (const flatbuffers::String *timestamp_logger_node :
932 *connection->timestamp_logger_nodes()) {
933 const Node *node = configuration::GetNode(
934 logged_configuration(), timestamp_logger_node->string_view());
935 message_bridge::ChannelTimestampFinder finder(
936 logged_configuration(), "log_reader", node);
937
938 // We are assuming here that all the maps are setup correctly to
939 // handle arbitrary timestamps. Apply the maps for this node to
940 // see what name this ends up with.
941 std::string name = finder.SplitChannelName(
942 pair.second.remapped_name, c->type()->str(), connection);
943 std::string unmapped_name = name;
944 configuration::HandleMaps(logged_configuration()->maps(), &name,
945 "aos.message_bridge.RemoteMessage",
946 node);
947 CHECK_NE(name, unmapped_name)
948 << ": Remote timestamp channel was not remapped, this is "
949 "very fishy";
950 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
951 fbb.CreateString(name);
952 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
953 fbb.CreateString("aos.message_bridge.RemoteMessage");
954 flatbuffers::Offset<flatbuffers::String> source_node_offset =
955 fbb.CreateString(timestamp_logger_node->string_view());
956
957 // Now, build a channel. Don't log it, 2 senders, and match the
958 // source frequency.
959 Channel::Builder channel_builder(fbb);
960 channel_builder.add_name(channel_name_offset);
961 channel_builder.add_type(channel_type_offset);
962 channel_builder.add_source_node(source_node_offset);
963 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
964 channel_builder.add_num_senders(2);
965 if (c->has_frequency()) {
966 channel_builder.add_frequency(c->frequency());
967 }
968 channel_offsets.emplace_back(channel_builder.Finish());
969 }
970 break;
971 }
972 }
973 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800974 }
Austin Schuh01b4c352020-09-21 23:09:39 -0700975
Austin Schuh0de30f32020-12-06 12:44:28 -0800976 // Now reconstruct the original channels, translating types as needed
977 for (const Channel *c : *base_config->channels()) {
978 // Search for a mapping channel.
979 std::string_view new_type = "";
980 for (auto &pair : remapped_channels_) {
981 const Channel *const remapped_channel =
982 logged_configuration()->channels()->Get(pair.first);
983 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
984 remapped_channel->type()->string_view() == c->type()->string_view()) {
985 new_type = pair.second.new_type;
986 break;
987 }
988 }
989
990 // Copy everything over.
991 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
992
993 // Add the schema if it doesn't exist.
994 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
995 CHECK(c->has_schema());
996 schema_map.insert(std::make_pair(c->type()->string_view(),
997 RecursiveCopyFlatBuffer(c->schema())));
998 }
999 }
1000
1001 // The MergeConfiguration API takes a vector, not a map. Convert.
1002 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1003 while (!schema_map.empty()) {
1004 schemas.emplace_back(std::move(schema_map.begin()->second));
1005 schema_map.erase(schema_map.begin());
1006 }
1007
1008 // Create the Configuration containing the new channels that we want to add.
1009 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1010 channels_offset =
1011 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1012
1013 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001014 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001015 if (base_config->maps()) {
1016 for (const Map *map : *base_config->maps()) {
1017 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1018 }
1019 }
1020
1021 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001022 for (const MapT &map : maps_) {
1023 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001024 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001025 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001026 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001027 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001028 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001029 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1030 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001031 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001032 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001033 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001034 match_builder.add_name(match_name_offset);
1035 match_builder.add_type(match_type_offset);
1036 if (!map.match->source_node.empty()) {
1037 match_builder.add_source_node(match_source_node_offset);
1038 }
1039 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1040
Austin Schuh0de30f32020-12-06 12:44:28 -08001041 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001042 rename_builder.add_name(rename_name_offset);
1043 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1044
Austin Schuh0de30f32020-12-06 12:44:28 -08001045 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001046 map_builder.add_match(match_offset);
1047 map_builder.add_rename(rename_offset);
1048 map_offsets.emplace_back(map_builder.Finish());
1049 }
1050
Austin Schuh0de30f32020-12-06 12:44:28 -08001051 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1052 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001053
Austin Schuh0de30f32020-12-06 12:44:28 -08001054 // And copy everything else over.
1055 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1056 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1057
1058 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1059 applications_offset =
1060 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1061
1062 // Now insert everything else in unmodified.
1063 ConfigurationBuilder configuration_builder(fbb);
1064 if (!channels_offset.IsNull()) {
1065 configuration_builder.add_channels(channels_offset);
1066 }
1067 if (!maps_offsets.IsNull()) {
1068 configuration_builder.add_maps(maps_offsets);
1069 }
1070 if (!nodes_offset.IsNull()) {
1071 configuration_builder.add_nodes(nodes_offset);
1072 }
1073 if (!applications_offset.IsNull()) {
1074 configuration_builder.add_applications(applications_offset);
1075 }
1076
1077 if (base_config->has_channel_storage_duration()) {
1078 configuration_builder.add_channel_storage_duration(
1079 base_config->channel_storage_duration());
1080 }
1081
1082 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1083 << ": Merging logic needs to be updated when the number of configuration "
1084 "fields changes.";
1085
1086 fbb.Finish(configuration_builder.Finish());
1087
1088 // Clean it up and return it! By using MergeConfiguration here, we'll
1089 // actually get a deduplicated config for free too.
1090 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1091 configuration::MergeConfiguration(
1092 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1093
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001094 remapped_configuration_buffer_ =
1095 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001096 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001097
1098 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001099
1100 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001101}
1102
Austin Schuh6f3babe2020-01-26 20:34:50 -08001103const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1104 const Channel *channel) {
1105 std::string_view channel_name = channel->name()->string_view();
1106 std::string_view channel_type = channel->type()->string_view();
1107 const int channel_index =
1108 configuration::ChannelIndex(logged_configuration(), channel);
1109 // If the channel is remapped, find the correct channel name to use.
1110 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001111 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001112 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001113 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001114 }
1115
Austin Schuhee711052020-08-24 16:06:09 -07001116 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001117 const Channel *remapped_channel = configuration::GetChannel(
1118 event_loop->configuration(), channel_name, channel_type,
1119 event_loop->name(), event_loop->node());
1120
1121 CHECK(remapped_channel != nullptr)
1122 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1123 << channel_type << "\"} because it is not in the provided configuration.";
1124
1125 return remapped_channel;
1126}
1127
Austin Schuh287d43d2020-12-04 20:19:33 -08001128LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1129 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1130
1131void LogReader::State::AddPeer(State *peer) {
1132 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1133 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1134 }
1135}
Austin Schuh858c9f32020-08-31 16:56:12 -07001136
1137EventLoop *LogReader::State::SetNodeEventLoopFactory(
1138 NodeEventLoopFactory *node_event_loop_factory) {
1139 node_event_loop_factory_ = node_event_loop_factory;
1140 event_loop_unique_ptr_ =
1141 node_event_loop_factory_->MakeEventLoop("log_reader");
1142 return event_loop_unique_ptr_.get();
1143}
1144
1145void LogReader::State::SetChannelCount(size_t count) {
1146 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001147 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001148 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001149 channel_source_state_.resize(count);
1150 factory_channel_index_.resize(count);
1151 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001152}
1153
1154void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001155 size_t logged_channel_index, size_t factory_channel_index,
1156 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001157 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001158 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001159 channels_[logged_channel_index] = std::move(sender);
1160 filters_[logged_channel_index] = filter;
1161 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1162
1163 if (source_state) {
1164 channel_source_state_[logged_channel_index] = source_state;
1165
1166 if (remote_timestamp_sender != nullptr) {
1167 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001168 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001169 }
1170 }
1171
1172 factory_channel_index_[logged_channel_index] = factory_channel_index;
1173}
1174
Austin Schuh287d43d2020-12-04 20:19:33 -08001175bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1176 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001177 uint32_t remote_queue_index = 0xffffffff;
1178
Austin Schuh287d43d2020-12-04 20:19:33 -08001179 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001180 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001181 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1182 ->queue_index_map_[timestamped_message.channel_index]
1183 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001184
Austin Schuh9942bae2021-01-07 22:06:44 -08001185 struct SentTimestamp {
1186 monotonic_clock::time_point monotonic_event_time;
1187 uint32_t queue_index;
1188 } search;
1189
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001190 CHECK_EQ(timestamped_message.monotonic_remote_time.boot, 0u);
1191 search.monotonic_event_time = timestamped_message.monotonic_remote_time.time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001192 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001193
1194 // Find the sent time if available.
1195 auto element = std::lower_bound(
1196 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001197 [](ContiguousSentTimestamp a, SentTimestamp b) {
1198 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001199 return true;
1200 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001201 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001202 return false;
1203 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001204
1205 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001206 return true;
1207 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001208 if (a.starting_queue_index >= b.queue_index) {
1209 return false;
1210 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001211
Austin Schuh9942bae2021-01-07 22:06:44 -08001212 // If it isn't clearly below or above, it is below. Since we return
1213 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001214 return false;
1215 });
1216
1217 // TODO(austin): Be a bit more principled here, but we will want to do that
1218 // after the logger rewrite. We hit this when one node finishes, but the
1219 // other node isn't done yet. So there is no send time, but there is a
1220 // receive time.
1221 if (element != queue_index_map->end()) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001222 CHECK_EQ(timestamped_message.monotonic_remote_time.boot, 0u);
1223
1224 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001225 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001226 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001227 element->ending_monotonic_event_time);
1228 CHECK_GE(timestamped_message.remote_queue_index,
1229 element->starting_queue_index);
1230 CHECK_LE(timestamped_message.remote_queue_index,
1231 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001232
Austin Schuh9942bae2021-01-07 22:06:44 -08001233 remote_queue_index = timestamped_message.remote_queue_index +
1234 element->actual_queue_index -
1235 element->starting_queue_index;
1236 } else {
1237 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001238 }
1239 }
1240
1241 // Send! Use the replayed queue index here instead of the logged queue index
1242 // for the remote queue index. This makes re-logging work.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001243 CHECK_EQ(timestamped_message.monotonic_remote_time.boot, 0u);
Austin Schuh287d43d2020-12-04 20:19:33 -08001244 const bool sent = sender->Send(
1245 timestamped_message.data.message().data()->Data(),
1246 timestamped_message.data.message().data()->size(),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001247 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001248 timestamped_message.realtime_remote_time, remote_queue_index,
1249 (channel_source_state_[timestamped_message.channel_index] != nullptr
1250 ? CHECK_NOTNULL(
1251 channel_source_state_[timestamped_message.channel_index])
1252 ->event_loop_->boot_uuid()
1253 : event_loop_->boot_uuid()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001254 if (!sent) return false;
1255
Austin Schuh287d43d2020-12-04 20:19:33 -08001256 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001257 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1258 // Nothing here, start a range with 0 length.
1259 ContiguousSentTimestamp timestamp;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001260 CHECK_EQ(timestamped_message.monotonic_event_time.boot, 0u);
Austin Schuh9942bae2021-01-07 22:06:44 -08001261 timestamp.starting_monotonic_event_time =
1262 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001263 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001264 timestamp.starting_queue_index = timestamp.ending_queue_index =
1265 timestamped_message.queue_index;
1266 timestamp.actual_queue_index = sender->sent_queue_index();
1267 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1268 timestamp);
1269 } else {
1270 // We've got something. See if the next timestamp is still contiguous. If
1271 // so, grow it.
1272 ContiguousSentTimestamp *back =
1273 &queue_index_map_[timestamped_message.channel_index]->back();
1274 if ((back->starting_queue_index - back->actual_queue_index) ==
1275 (timestamped_message.queue_index - sender->sent_queue_index())) {
1276 back->ending_queue_index = timestamped_message.queue_index;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001277 CHECK_EQ(timestamped_message.monotonic_event_time.boot, 0u);
Austin Schuh9942bae2021-01-07 22:06:44 -08001278 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001279 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001280 } else {
1281 // Otherwise, make a new one.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001282 CHECK_EQ(timestamped_message.monotonic_event_time.boot, 0u);
Austin Schuh9942bae2021-01-07 22:06:44 -08001283 ContiguousSentTimestamp timestamp;
1284 timestamp.starting_monotonic_event_time =
1285 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001286 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001287 timestamp.starting_queue_index = timestamp.ending_queue_index =
1288 timestamped_message.queue_index;
1289 timestamp.actual_queue_index = sender->sent_queue_index();
1290 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1291 timestamp);
1292 }
1293 }
1294
1295 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1296 // queue index diverge a couple of elements, which would be a very small
1297 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001298 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1299 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001300 flatbuffers::FlatBufferBuilder fbb;
1301 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001302 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1303 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001304
Austin Schuh969cd602021-01-03 00:09:45 -08001305 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001306
1307 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001308 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001309
1310 // Swap the remote and sent metrics. They are from the sender's
1311 // perspective, not the receiver's perspective.
1312 message_header_builder.add_monotonic_sent_time(
1313 sender->monotonic_sent_time().time_since_epoch().count());
1314 message_header_builder.add_realtime_sent_time(
1315 sender->realtime_sent_time().time_since_epoch().count());
1316 message_header_builder.add_queue_index(sender->sent_queue_index());
1317
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001318 CHECK_EQ(timestamped_message.monotonic_remote_time.boot, 0u);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001319 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001320 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1321 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001322 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001323 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001324
1325 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001326 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001327
Austin Schuh969cd602021-01-03 00:09:45 -08001328 fbb.Finish(message_header_builder.Finish());
1329
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001330 CHECK_EQ(timestamped_message.monotonic_timestamp_time.boot, 0u);
Austin Schuh969cd602021-01-03 00:09:45 -08001331 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1332 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001333 timestamped_message.monotonic_timestamp_time.time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001334 }
1335
1336 return true;
1337}
1338
Austin Schuh969cd602021-01-03 00:09:45 -08001339LogReader::RemoteMessageSender::RemoteMessageSender(
1340 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1341 : event_loop_(event_loop),
1342 sender_(std::move(sender)),
1343 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1344
1345void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1346 if (remote_timestamps_.empty()) {
1347 CHECK_NOTNULL(timer_);
1348 timer_->Disable();
1349 scheduled_time_ = monotonic_clock::min_time;
1350 return;
1351 }
1352
1353 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1354 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001355 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001356 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001357 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1358 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001359 }
1360}
1361
1362void LogReader::RemoteMessageSender::Send(
1363 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
1364 monotonic_clock::time_point monotonic_timestamp_time) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001365 // There are 2 variants of logs.
1366 // 1) Logs without monotonic_timestamp_time
1367 // 2) Logs with monotonic_timestamp_time
1368 //
1369 // As of Jan 2021, we shouldn't have any more logs without
1370 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1371 // the effort of saving.
1372 //
1373 // This gives us 3 cases, 2 of which are undistinguishable.
1374 // 1) Old log without monotonic_timestamp_time.
1375 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1376 // remotely so we actually have monotonic_timestamp_time.
1377 // 3) New log, but the timestamp was logged on the node receiving the message
1378 // so there is no monotonic_timestamp_time.
1379 //
1380 // Our goal when replaying is to accurately reproduce the state of the world
1381 // present when logging. If a timestamp wasn't sent back across the network,
1382 // we shouldn't replay one back across the network.
1383 //
1384 // Given that we don't really care about 1, we can use the presence of the
1385 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1386 // monotonic_timestamp_time, this means the message was logged locally and
1387 // remote timestamps can be ignored.
Austin Schuh969cd602021-01-03 00:09:45 -08001388 if (monotonic_timestamp_time == monotonic_clock::min_time) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001389 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001390 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001391
1392 remote_timestamps_.emplace(
1393 std::upper_bound(
1394 remote_timestamps_.begin(), remote_timestamps_.end(),
1395 monotonic_timestamp_time,
1396 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1397 const Timestamp &timestamp) {
1398 return monotonic_timestamp_time <
1399 timestamp.monotonic_timestamp_time;
1400 }),
1401 std::move(remote_message), monotonic_timestamp_time);
1402 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001403}
1404
1405void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001406 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1407 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001408 CHECK(!remote_timestamps_.empty());
1409
1410 // Send out all timestamps at the currently scheduled time.
1411 while (remote_timestamps_.front().monotonic_timestamp_time ==
1412 scheduled_time_) {
1413 sender_.Send(std::move(remote_timestamps_.front().remote_message));
1414 remote_timestamps_.pop_front();
1415 if (remote_timestamps_.empty()) {
1416 break;
1417 }
1418 }
1419 scheduled_time_ = monotonic_clock::min_time;
1420
1421 ScheduleTimestamp();
1422}
1423
1424LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001425 const Channel *channel, const Connection *connection) {
1426 message_bridge::ChannelTimestampFinder finder(event_loop_);
1427 // Look at any pre-created channel/connection pairs.
1428 {
1429 auto it =
1430 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1431 if (it != channel_timestamp_loggers_.end()) {
1432 return it->second.get();
1433 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001434 }
1435
Austin Schuh61e973f2021-02-21 21:43:56 -08001436 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1437 // to.
1438 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1439
1440 {
1441 // See if that has been created before. If so, cache it in
1442 // channel_timestamp_loggers_ and return.
1443 auto it = timestamp_loggers_.find(timestamp_channel);
1444 if (it != timestamp_loggers_.end()) {
1445 CHECK(channel_timestamp_loggers_
1446 .try_emplace(std::make_pair(channel, connection), it->second)
1447 .second);
1448 return it->second.get();
1449 }
1450 }
1451
1452 // Otherwise, make a sender, save it, and cache it.
1453 auto result = channel_timestamp_loggers_.try_emplace(
1454 std::make_pair(channel, connection),
1455 std::make_shared<RemoteMessageSender>(
1456 event_loop()->MakeSender<RemoteMessage>(
1457 timestamp_channel->name()->string_view()),
1458 event_loop()));
1459
1460 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1461 .second);
1462 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001463}
1464
Austin Schuhdda74ec2021-01-03 19:30:37 -08001465TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001466 CHECK(timestamp_mapper_ != nullptr);
1467 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1468 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001469
Austin Schuhe639ea12021-01-25 13:00:22 -08001470 TimestampedMessage result = std::move(*result_ptr);
1471
Austin Schuh2f8fd752020-09-01 22:38:28 -07001472 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001473 << result.monotonic_event_time;
1474 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001475 SeedSortedMessages();
1476
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001477 CHECK_EQ(result.monotonic_remote_time.boot, 0u);
1478
1479 if (result.monotonic_remote_time.time != monotonic_clock::min_time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001480 message_bridge::NoncausalOffsetEstimator *filter =
1481 filters_[result.channel_index];
1482 CHECK(filter != nullptr);
1483
1484 // TODO(austin): We probably want to push this down into the timestamp
1485 // mapper directly.
Austin Schuh3d94be02021-02-12 23:15:20 -08001486 filter->Pop(event_loop_->node(), event_loop_->monotonic_now());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001487 }
Austin Schuh5ee56872021-01-30 16:53:34 -08001488 VLOG(1) << "Popped " << result
1489 << configuration::CleanedChannelToString(
1490 event_loop_->configuration()->channels()->Get(
1491 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001492 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001493}
1494
1495monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
Austin Schuhe639ea12021-01-25 13:00:22 -08001496 if (timestamp_mapper_ == nullptr) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001497 return monotonic_clock::max_time;
1498 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001499 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1500 if (result_ptr == nullptr) {
1501 return monotonic_clock::max_time;
1502 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001503 CHECK_EQ(result_ptr->monotonic_event_time.boot, 0u);
Austin Schuhe639ea12021-01-25 13:00:22 -08001504 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001505 << result_ptr->monotonic_event_time.time;
1506 return result_ptr->monotonic_event_time.time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001507}
1508
1509void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001510 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001511
Austin Schuhe639ea12021-01-25 13:00:22 -08001512 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1513 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001514}
1515
1516void LogReader::State::Deregister() {
1517 for (size_t i = 0; i < channels_.size(); ++i) {
1518 channels_[i].reset();
1519 }
Austin Schuh61e973f2021-02-21 21:43:56 -08001520 channel_timestamp_loggers_.clear();
1521 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001522 event_loop_unique_ptr_.reset();
1523 event_loop_ = nullptr;
1524 timer_handler_ = nullptr;
1525 node_event_loop_factory_ = nullptr;
1526}
1527
Austin Schuhe309d2a2019-11-29 13:25:21 -08001528} // namespace logger
1529} // namespace aos