blob: 2eb3094a7a30c62cb7b5de6448cf81d75e62bda9 [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 Schuhf6f9bf32020-10-11 14:37:43 -070014#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080015#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080016#include "aos/flatbuffer_merge.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080017#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080018#include "aos/network/remote_message_generated.h"
19#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080020#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080021#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070023#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070024#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080025#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080026#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027
Austin Schuh15649d62019-12-28 16:36:38 -080028DEFINE_bool(skip_missing_forwarding_entries, false,
29 "If true, drop any forwarding entries with missing data. If "
30 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080031
Austin Schuh0ca1fd32020-12-18 22:53:05 -080032DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080033
Austin Schuh2f8fd752020-09-01 22:38:28 -070034DEFINE_bool(skip_order_validation, false,
35 "If true, ignore any out of orderness in replay");
36
Austin Schuhf0688662020-12-19 15:37:45 -080037DEFINE_double(
38 time_estimation_buffer_seconds, 2.0,
39 "The time to buffer ahead in the log file to accurately reconstruct time.");
40
Austin Schuhe309d2a2019-11-29 13:25:21 -080041namespace aos {
42namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070043namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080044
Austin Schuh315b96b2020-12-11 21:21:12 -080045std::string LogFileVectorToString(std::vector<LogFile> log_files) {
46 std::stringstream ss;
Austin Schuh297d2352021-01-21 19:02:17 -080047 for (const auto &f : log_files) {
Austin Schuh315b96b2020-12-11 21:21:12 -080048 ss << f << "\n";
49 }
50 return ss.str();
51}
52
Austin Schuh0de30f32020-12-06 12:44:28 -080053// Copies the channel, removing the schema as we go. If new_name is provided,
54// it is used instead of the name inside the channel. If new_type is provided,
55// it is used instead of the type in the channel.
56flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
57 std::string_view new_name,
58 std::string_view new_type,
59 flatbuffers::FlatBufferBuilder *fbb) {
60 flatbuffers::Offset<flatbuffers::String> name_offset =
61 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
62 : new_name);
63 flatbuffers::Offset<flatbuffers::String> type_offset =
64 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
65 flatbuffers::Offset<flatbuffers::String> source_node_offset =
66 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
67 : 0;
68
69 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
70 destination_nodes_offset =
71 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
72
73 flatbuffers::Offset<
74 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
75 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
76
77 Channel::Builder channel_builder(*fbb);
78 channel_builder.add_name(name_offset);
79 channel_builder.add_type(type_offset);
80 if (c->has_frequency()) {
81 channel_builder.add_frequency(c->frequency());
82 }
83 if (c->has_max_size()) {
84 channel_builder.add_max_size(c->max_size());
85 }
86 if (c->has_num_senders()) {
87 channel_builder.add_num_senders(c->num_senders());
88 }
89 if (c->has_num_watchers()) {
90 channel_builder.add_num_watchers(c->num_watchers());
91 }
92 if (!source_node_offset.IsNull()) {
93 channel_builder.add_source_node(source_node_offset);
94 }
95 if (!destination_nodes_offset.IsNull()) {
96 channel_builder.add_destination_nodes(destination_nodes_offset);
97 }
98 if (c->has_logger()) {
99 channel_builder.add_logger(c->logger());
100 }
101 if (!logger_nodes_offset.IsNull()) {
102 channel_builder.add_logger_nodes(logger_nodes_offset);
103 }
104 if (c->has_read_method()) {
105 channel_builder.add_read_method(c->read_method());
106 }
107 if (c->has_num_readers()) {
108 channel_builder.add_num_readers(c->num_readers());
109 }
110 return channel_builder.Finish();
111}
112
Austin Schuhe309d2a2019-11-29 13:25:21 -0800113namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800114using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700115} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800116
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800117LogReader::LogReader(std::string_view filename,
118 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800119 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800120
Austin Schuh287d43d2020-12-04 20:19:33 -0800121LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800122 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800123 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800124 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800125 CHECK_GT(log_files_.size(), 0u);
126 {
127 // Validate that we have the same config everwhere. This will be true if
128 // all the parts were sorted together and the configs match.
129 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800130 for (const LogFile &log_file : log_files_) {
131 if (log_file.config.get() == nullptr) {
132 LOG(FATAL) << "Couldn't find a config in " << log_file;
133 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800134 if (config == nullptr) {
135 config = log_file.config.get();
136 } else {
137 CHECK_EQ(config, log_file.config.get());
138 }
139 }
140 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800141
Austin Schuh6331ef92020-01-07 18:28:09 -0800142 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800143
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700144 // Remap all existing remote timestamp channels. They will be recreated, and
145 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700146 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800147 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
148 "log_reader", node);
149
150 absl::btree_set<std::string_view> remote_nodes;
151
152 for (const Channel *channel : *logged_configuration()->channels()) {
153 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
154 continue;
155 }
156 if (!channel->has_destination_nodes()) {
157 continue;
158 }
159 for (const Connection *connection : *channel->destination_nodes()) {
160 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
161 node)) {
162 // Start by seeing if the split timestamp channels are being used for
163 // this message. If so, remap them.
164 const Channel *timestamp_channel = configuration::GetChannel(
165 logged_configuration(),
166 finder.SplitChannelName(channel, connection),
167 RemoteMessage::GetFullyQualifiedName(), "", node, true);
168
169 if (timestamp_channel != nullptr) {
170 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
171 RemapLoggedChannel<RemoteMessage>(
172 timestamp_channel->name()->string_view(), node);
173 }
174 continue;
175 }
176
177 // Otherwise collect this one up as a node to look for a combined
178 // channel from. It is more efficient to compare nodes than channels.
179 remote_nodes.insert(connection->name()->string_view());
180 }
181 }
182 }
183
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700184 std::vector<const Node *> timestamp_logger_nodes =
185 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800186 for (const std::string_view remote_node : remote_nodes) {
187 const std::string channel = finder.CombinedChannelName(remote_node);
188
Austin Schuh0de30f32020-12-06 12:44:28 -0800189 // See if the log file is an old log with MessageHeader channels in it, or
190 // a newer log with RemoteMessage. If we find an older log, rename the
191 // type too along with the name.
192 if (HasChannel<MessageHeader>(channel, node)) {
193 CHECK(!HasChannel<RemoteMessage>(channel, node))
194 << ": Can't have both a MessageHeader and RemoteMessage remote "
195 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800196 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
197 // careful about updating the config, but there are fewer and fewer logs
198 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800199 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
200 "aos.message_bridge.RemoteMessage");
201 } else {
202 CHECK(HasChannel<RemoteMessage>(channel, node))
203 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
204 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
205 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800206 // Only bother to remap if there's something on the channel. We can
207 // tell if the channel was marked NOT_LOGGED or not. This makes the
208 // config not change un-necesarily when we replay a log with NOT_LOGGED
209 // messages.
210 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
211 RemapLoggedChannel<RemoteMessage>(channel, node);
212 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800213 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700214 }
215 }
216
Austin Schuh6aa77be2020-02-22 21:06:40 -0800217 if (replay_configuration) {
218 CHECK_EQ(configuration::MultiNode(configuration()),
219 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700220 << ": Log file and replay config need to both be multi or single "
221 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800222 }
223
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800225 states_.emplace_back(std::make_unique<State>(
226 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800227 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800228 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700229 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800230 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700231 << ": Log file and replay config need to have matching nodes "
232 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700233 for (const Node *node : *logged_configuration()->nodes()) {
234 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700235 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
236 << " in logged config that is not present in the replay "
237 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700238 }
239 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800240 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800241 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800242 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800243}
244
Austin Schuh6aa77be2020-02-22 21:06:40 -0800245LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700246 if (event_loop_factory_unique_ptr_) {
247 Deregister();
248 } else if (event_loop_factory_ != nullptr) {
249 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
250 "is destroyed";
251 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700252 // Zero out some buffers. It's easy to do use-after-frees on these, so make
253 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700254 if (remapped_configuration_buffer_) {
255 remapped_configuration_buffer_->Wipe();
256 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800257}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800258
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800259const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800260 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800261}
262
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800263const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800264 return remapped_configuration_;
265}
266
Austin Schuh07676622021-01-21 18:59:17 -0800267std::vector<const Node *> LogReader::LoggedNodes() const {
268 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800269}
Austin Schuh15649d62019-12-28 16:36:38 -0800270
Austin Schuh11d43732020-09-21 17:28:30 -0700271monotonic_clock::time_point LogReader::monotonic_start_time(
272 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800273 State *state =
274 states_[configuration::GetNodeIndex(configuration(), node)].get();
275 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
276
Austin Schuh858c9f32020-08-31 16:56:12 -0700277 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800278}
279
Austin Schuh11d43732020-09-21 17:28:30 -0700280realtime_clock::time_point LogReader::realtime_start_time(
281 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800282 State *state =
283 states_[configuration::GetNodeIndex(configuration(), node)].get();
284 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
285
Austin Schuh858c9f32020-08-31 16:56:12 -0700286 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800287}
288
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800289void LogReader::Register() {
290 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800291 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800292 Register(event_loop_factory_unique_ptr_.get());
293}
294
Austin Schuh92547522019-12-28 14:33:43 -0800295void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800296 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700297 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800298 filters_ =
299 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800300 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuhfe3fb342021-01-16 18:50:37 -0800301 FLAGS_skip_order_validation,
302 chrono::duration_cast<chrono::nanoseconds>(
303 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800304
Austin Schuhe639ea12021-01-25 13:00:22 -0800305 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700306 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800307 const size_t node_index =
308 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800309 std::vector<LogParts> filtered_parts = FilterPartsForNode(
310 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800311
312 // Confirm that all the parts are from the same boot if there are enough
313 // parts to not be from the same boot.
314 if (filtered_parts.size() > 1u) {
315 for (size_t i = 1; i < filtered_parts.size(); ++i) {
316 CHECK_EQ(filtered_parts[i].source_boot_uuid,
317 filtered_parts[0].source_boot_uuid)
Austin Schuh8902fa52021-03-14 22:39:24 -0700318 << ": Found parts from different boots for node "
319 << node->name()->string_view() << " "
Austin Schuh315b96b2020-12-11 21:21:12 -0800320 << LogFileVectorToString(log_files_);
321 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800322 if (!filtered_parts[0].source_boot_uuid.empty()) {
323 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
324 filtered_parts[0].source_boot_uuid);
325 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800326 }
327
Austin Schuh287d43d2020-12-04 20:19:33 -0800328 states_[node_index] = std::make_unique<State>(
329 filtered_parts.size() == 0u
330 ? nullptr
331 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800332 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700333 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700334 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700335
336 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800337 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800338 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800339 filters_->SetTimestampMappers(std::move(timestamp_mappers));
340
341 // Note: this needs to be set before any times are pulled, or we won't observe
342 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800343 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700344
Austin Schuh287d43d2020-12-04 20:19:33 -0800345 for (const Node *node : configuration::GetNodes(configuration())) {
346 const size_t node_index =
347 configuration::GetNodeIndex(configuration(), node);
348 State *state = states_[node_index].get();
349 for (const Node *other_node : configuration::GetNodes(configuration())) {
350 const size_t other_node_index =
351 configuration::GetNodeIndex(configuration(), other_node);
352 State *other_state = states_[other_node_index].get();
353 if (other_state != state) {
354 state->AddPeer(other_state);
355 }
356 }
357 }
358
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700359 // Register after making all the State objects so we can build references
360 // between them.
361 for (const Node *node : configuration::GetNodes(configuration())) {
362 const size_t node_index =
363 configuration::GetNodeIndex(configuration(), node);
364 State *state = states_[node_index].get();
365
366 Register(state->event_loop());
367 }
368
James Kuszmaul46d82582020-05-09 19:50:09 -0700369 if (live_nodes_ == 0) {
370 LOG(FATAL)
371 << "Don't have logs from any of the nodes in the replay config--are "
372 "you sure that the replay config matches the original config?";
373 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800374
Austin Schuh87dd3832021-01-01 23:07:31 -0800375 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800376
Austin Schuh858c9f32020-08-31 16:56:12 -0700377 for (std::unique_ptr<State> &state : states_) {
378 state->SeedSortedMessages();
379 }
380
Austin Schuh2f8fd752020-09-01 22:38:28 -0700381 // We want to start the log file at the last start time of the log files
382 // from all the nodes. Compute how long each node's simulation needs to run
383 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800384 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800385
Austin Schuh2f8fd752020-09-01 22:38:28 -0700386 // TODO(austin): We want an "OnStart" callback for each node rather than
387 // running until the last node.
388
Austin Schuh8bd96322020-02-13 21:18:22 -0800389 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700390 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
391 << MaybeNodeName(state->event_loop()->node()) << "now "
392 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -0800393 if (state->monotonic_start_time() == monotonic_clock::min_time) {
394 continue;
395 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700396 // And start computing the start time on the distributed clock now that
397 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -0700398 start_time = std::max(
399 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -0800400 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700401
Austin Schuh87dd3832021-01-01 23:07:31 -0800402 // TODO(austin): If a node doesn't have a start time, we might not queue
403 // enough. If this happens, we'll explode with a frozen error eventually.
404
Austin Schuh2f8fd752020-09-01 22:38:28 -0700405 CHECK_GE(start_time, distributed_clock::epoch())
406 << ": Hmm, we have a node starting before the start of time. Offset "
407 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -0800408
Austin Schuh6f3babe2020-01-26 20:34:50 -0800409 // Forwarding is tracked per channel. If it is enabled, we want to turn it
410 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700411 // nodes, and also replayed on the other nodes. This may not satisfy all
412 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800413 if (configuration::MultiNode(event_loop_factory_->configuration())) {
414 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
415 const Channel *channel = logged_configuration()->channels()->Get(i);
416 const Node *node = configuration::GetNode(
417 configuration(), channel->source_node()->string_view());
418
Austin Schuh8bd96322020-02-13 21:18:22 -0800419 State *state =
420 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800421
422 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -0700423 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800424
425 event_loop_factory_->DisableForwarding(remapped_channel);
426 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700427
428 // If we are replaying a log, we don't want a bunch of redundant messages
429 // from both the real message bridge and simulated message bridge.
430 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800431 }
432
Austin Schuhcde938c2020-02-02 17:30:07 -0800433 // While we are starting the system up, we might be relying on matching data
434 // to timestamps on log files where the timestamp log file starts before the
435 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800436 {
437 const bool prior_ignore_missing_data = ignore_missing_data_;
438 ignore_missing_data_ = true;
439 VLOG(1) << "Running until " << start_time << " in Register";
440 event_loop_factory_->RunFor(start_time.time_since_epoch());
441 VLOG(1) << "At start time";
442 // Now that we are running for real, missing data means that the log file is
443 // corrupted or went wrong.
444 ignore_missing_data_ = prior_ignore_missing_data;
445 }
Austin Schuh92547522019-12-28 14:33:43 -0800446
Austin Schuh8bd96322020-02-13 21:18:22 -0800447 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700448 // Make the RT clock be correct before handing it to the user.
449 if (state->realtime_start_time() != realtime_clock::min_time) {
450 state->SetRealtimeOffset(state->monotonic_start_time(),
451 state->realtime_start_time());
452 }
453 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
454 << MaybeNodeName(state->event_loop()->node()) << "now "
455 << state->monotonic_now();
456 }
457
458 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800459 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800460 }
461}
462
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800464 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800465 if (filters_) {
466 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800467 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800468 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800469}
470
Austin Schuhe309d2a2019-11-29 13:25:21 -0800471void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800472 State *state =
473 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
474 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800475
Austin Schuh858c9f32020-08-31 16:56:12 -0700476 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800477
Tyler Chatow67ddb032020-01-12 14:30:04 -0800478 // We don't run timing reports when trying to print out logged data, because
479 // otherwise we would end up printing out the timing reports themselves...
480 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800481 event_loop->SkipTimingReport();
482 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -0800483
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700484 for (size_t logged_channel_index = 0;
485 logged_channel_index < logged_configuration()->channels()->size();
486 ++logged_channel_index) {
487 const Channel *channel = RemapChannel(
488 event_loop,
489 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800490
Austin Schuh532656d2021-01-11 10:17:18 -0800491 if (channel->logger() == LoggerConfig::NOT_LOGGED) {
492 continue;
493 }
494
Austin Schuh2f8fd752020-09-01 22:38:28 -0700495 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -0800496 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700497
498 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800499
500 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
501 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700502 // We've got a message which is being forwarded to this node.
503 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -0800504 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700505 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800506
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700507 // Delivery timestamps are supposed to be logged back on the source node.
508 // Configure remote timestamps to be sent.
Austin Schuh61e973f2021-02-21 21:43:56 -0800509 const Connection *connection =
510 configuration::ConnectionToNode(channel, event_loop->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700511 const bool delivery_time_is_logged =
Austin Schuh61e973f2021-02-21 21:43:56 -0800512 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
513 source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700514
515 source_state =
516 states_[configuration::GetNodeIndex(configuration(), source_node)]
517 .get();
518
519 if (delivery_time_is_logged) {
520 remote_timestamp_sender =
Austin Schuh61e973f2021-02-21 21:43:56 -0800521 source_state->RemoteTimestampSender(channel, connection);
Austin Schuh8bd96322020-02-13 21:18:22 -0800522 }
523 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700524
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700525 state->SetChannel(
526 logged_channel_index,
527 configuration::ChannelIndex(event_loop->configuration(), channel),
528 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
529 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800530 }
531
Austin Schuh6aa77be2020-02-22 21:06:40 -0800532 // If we didn't find any log files with data in them, we won't ever get a
533 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -0800534 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800535 return;
536 }
537
Austin Schuh858c9f32020-08-31 16:56:12 -0700538 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700539 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
540 << "at " << state->event_loop()->context().monotonic_event_time
541 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700542 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800543 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700544 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800545 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800546 event_loop_factory_->Exit();
547 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800548 return;
549 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700550
Austin Schuhdda74ec2021-01-03 19:30:37 -0800551 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -0800552
Austin Schuhe309d2a2019-11-29 13:25:21 -0800553 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700554 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700555 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800556 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700557 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
558 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800559 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700560 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -0800561 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700562 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800563 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700564 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800565 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700566 << "): " << FlatbufferToJson(state->event_loop()->node())
567 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800568 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700569 << state->DebugString();
570 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800571
Austin Schuh287d43d2020-12-04 20:19:33 -0800572 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -0700573 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -0800574 event_loop_factory_ != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800575 if (timestamped_message.data.span().size() != 0u) {
576 if (timestamped_message.monotonic_remote_time !=
577 monotonic_clock::min_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800578 // Confirm that the message was sent on the sending node before the
579 // destination node (this node). As a proxy, do this by making sure
580 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800581 //
582 // TODO(austin): <= means that the cause message (which we know) could
583 // happen after the effect even though we know they are at the same
584 // time. I doubt anyone will notice for a bit, but we should really
585 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700586 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800587 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -0800588 timestamped_message.monotonic_remote_time,
589 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700590 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800591 << state->remote_node(timestamped_message.channel_index)
592 ->name()
593 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800594 << " while trying to send a message on "
595 << configuration::CleanedChannelToString(
596 logged_configuration()->channels()->Get(
597 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700598 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -0800599 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -0800600 state->monotonic_remote_now(
601 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700602 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800603 << "Check failed: timestamped_message.monotonic_remote_time < "
604 "state->monotonic_remote_now(timestamped_message.channel_"
605 "index) ("
606 << timestamped_message.monotonic_remote_time << " vs. "
607 << state->monotonic_remote_now(
608 timestamped_message.channel_index)
609 << ") " << state->event_loop()->node()->name()->string_view()
610 << " to "
611 << state->remote_node(timestamped_message.channel_index)
612 ->name()
613 ->string_view()
614 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700615 << " ("
616 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800617 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700618 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800619 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700620 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800621 timestamped_message.channel_index,
622 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700623 << ") " << state->DebugString();
624 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800625 }
626
Austin Schuh15649d62019-12-28 16:36:38 -0800627 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -0800628 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
629 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800630
Austin Schuh2f8fd752020-09-01 22:38:28 -0700631 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800632 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700633 // TODO(austin): std::move channel_data in and make that efficient in
634 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800635 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800636 } else if (!ignore_missing_data_ &&
Austin Schuh5ee56872021-01-30 16:53:34 -0800637 // When starting up, we can have data which was sent before the
638 // log starts, but the timestamp was after the log starts. This
639 // is unreasonable to avoid, so ignore the missing data.
640 timestamped_message.monotonic_remote_time >=
641 state->monotonic_remote_start_time(
642 timestamped_message.channel_index) &&
Austin Schuhdda74ec2021-01-03 19:30:37 -0800643 !FLAGS_skip_missing_forwarding_entries) {
Austin Schuh5ee56872021-01-30 16:53:34 -0800644 // We've found a timestamp without data that we expect to have data for.
645 // This likely means that we are at the end of the log file. Record it
646 // and CHECK that in the rest of the log file, we don't find any more
647 // data on that channel. Not all channels will end at the same point in
648 // time since they can be in different files.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800649 VLOG(1) << "Found the last message on channel "
650 << timestamped_message.channel_index;
651
Austin Schuh2bb80e02021-03-20 21:46:17 -0700652 // The user might be working with log files from 1 node but forgot to
653 // configure the infrastructure to log data for a remote channel on that
654 // node. That can be very hard to debug, even though the log reader is
655 // doing the right thing. At least log a warning in that case and tell
656 // the user what is happening so they can either update their config to
657 // log the channel or can find a log with the data.
658 {
659 const std::vector<std::string> logger_nodes =
660 FindLoggerNodes(log_files_);
661 if (logger_nodes.size()) {
662 // We have old logs which don't have the logger nodes logged. In
663 // that case, we can't be helpful :(
664 bool data_logged = false;
665 const Channel *channel = logged_configuration()->channels()->Get(
666 timestamped_message.channel_index);
667 for (const std::string &node : logger_nodes) {
668 data_logged |=
669 configuration::ChannelMessageIsLoggedOnNode(channel, node);
670 }
671 if (!data_logged) {
672 LOG(WARNING) << "Got a timestamp without any logfiles which "
673 "could contain data for channel "
674 << configuration::CleanedChannelToString(channel);
675 LOG(WARNING) << "Only have logs logged on ["
676 << absl::StrJoin(logger_nodes, ", ") << "]";
677 LOG(WARNING)
678 << "Dropping the rest of the data on "
679 << state->event_loop()->node()->name()->string_view();
680 LOG(WARNING)
681 << "Consider using --skip_missing_forwarding_entries to "
682 "bypass this, update your config to log it, or add data "
683 "from one of the nodes it is logged on.";
684 }
685 }
686 }
687
Austin Schuhdda74ec2021-01-03 19:30:37 -0800688 // Vector storing if we've seen a nullptr message or not per channel.
689 std::vector<bool> last_message;
690 last_message.resize(logged_configuration()->channels()->size(), false);
691
692 last_message[timestamped_message.channel_index] = true;
693
694 // Now that we found the end of one channel, artificially stop the
695 // rest. It is confusing when part of your data gets replayed but not
Austin Schuh5ee56872021-01-30 16:53:34 -0800696 // all. Read the rest of the messages and drop them on the floor while
697 // doing some basic validation.
Austin Schuh858c9f32020-08-31 16:56:12 -0700698 while (state->OldestMessageTime() != monotonic_clock::max_time) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800699 TimestampedMessage next = state->PopOldest();
700 // Make sure that once we have seen the last message on a channel,
701 // data doesn't start back up again. If the user wants to play
702 // through events like this, they can set
703 // --skip_missing_forwarding_entries or ignore_missing_data_.
704 CHECK_LT(next.channel_index, last_message.size());
705 if (next.data.span().size() == 0u) {
706 last_message[next.channel_index] = true;
707 } else {
708 if (last_message[next.channel_index]) {
709 LOG(FATAL)
710 << "Found missing data in the middle of the log file on "
711 "channel "
712 << next.channel_index << " Last "
713 << last_message[next.channel_index] << state->DebugString();
714 }
715 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800716 }
Austin Schuh92547522019-12-28 14:33:43 -0800717 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800718 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800719 LOG(WARNING)
720 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800721 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -0800722 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -0700723 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -0800724 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -0700725 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -0800726 }
727
Austin Schuh858c9f32020-08-31 16:56:12 -0700728 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800729 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700730 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
731 << "wakeup for " << next_time << "("
732 << state->ToDistributedClock(next_time)
733 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700734 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -0800735 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 VLOG(1) << MaybeNodeName(state->event_loop()->node())
737 << "No next message, scheduling shutdown";
738 // Set a timer up immediately after now to die. If we don't do this,
739 // then the senders waiting on the message we just read will never get
740 // called.
Austin Schuheecb9282020-01-08 17:43:30 -0800741 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700742 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
743 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -0800744 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800745 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800746
Austin Schuh2f8fd752020-09-01 22:38:28 -0700747 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
748 << state->event_loop()->context().monotonic_event_time << " now "
749 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700750 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800751
Austin Schuh6f3babe2020-01-26 20:34:50 -0800752 ++live_nodes_;
753
Austin Schuh858c9f32020-08-31 16:56:12 -0700754 if (state->OldestMessageTime() != monotonic_clock::max_time) {
755 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -0800756 }
757}
758
759void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800760 // Make sure that things get destroyed in the correct order, rather than
761 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -0800762 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700763 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800764 }
Austin Schuh92547522019-12-28 14:33:43 -0800765
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800766 event_loop_factory_unique_ptr_.reset();
767 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800768}
769
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800770void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800771 std::string_view add_prefix,
772 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800773 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
774 const Channel *const channel = logged_configuration()->channels()->Get(ii);
775 if (channel->name()->str() == name &&
776 channel->type()->string_view() == type) {
777 CHECK_EQ(0u, remapped_channels_.count(ii))
778 << "Already remapped channel "
779 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800780 RemappedChannel remapped_channel;
781 remapped_channel.remapped_name =
782 std::string(add_prefix) + std::string(name);
783 remapped_channel.new_type = new_type;
784 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800785 VLOG(1) << "Remapping channel "
786 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -0800787 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -0800788 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800789 return;
790 }
791 }
792 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
793 << type;
794}
795
Austin Schuh01b4c352020-09-21 23:09:39 -0700796void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
797 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800798 std::string_view add_prefix,
799 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -0700800 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
801 const Channel *remapped_channel =
802 configuration::GetChannel(logged_configuration(), name, type, "", node);
803 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
804 << "\", \"type\": \"" << type << "\"}";
805 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
806 << "\"}";
807 VLOG(1) << "Remapped "
808 << aos::configuration::StrippedChannelToString(remapped_channel);
809
810 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
811 // we want it to degrade if the heuristics fail to just work.
812 //
813 // The easiest way to do this is going to be incredibly specific and verbose.
814 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
815 // /original/0/spray. Then, create a map from /original/spray to
816 // /original/0/spray for just the type we were asked for.
817 if (name != remapped_channel->name()->string_view()) {
818 MapT new_map;
819 new_map.match = std::make_unique<ChannelT>();
820 new_map.match->name = absl::StrCat(add_prefix, name);
821 new_map.match->type = type;
822 if (node != nullptr) {
823 new_map.match->source_node = node->name()->str();
824 }
825 new_map.rename = std::make_unique<ChannelT>();
826 new_map.rename->name =
827 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
828 maps_.emplace_back(std::move(new_map));
829 }
830
831 const size_t channel_index =
832 configuration::ChannelIndex(logged_configuration(), remapped_channel);
833 CHECK_EQ(0u, remapped_channels_.count(channel_index))
834 << "Already remapped channel "
835 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800836
837 RemappedChannel remapped_channel_struct;
838 remapped_channel_struct.remapped_name =
839 std::string(add_prefix) +
840 std::string(remapped_channel->name()->string_view());
841 remapped_channel_struct.new_type = new_type;
842 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -0700843 MakeRemappedConfig();
844}
845
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800846void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -0800847 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800848 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700849 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -0800850 << ": Can't change the mapping after the events are scheduled.";
851 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800852 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800853
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800854 // If no remapping occurred and we are using the original config, then there
855 // is nothing interesting to do here.
856 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800857 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800858 return;
859 }
860 // Config to copy Channel definitions from. Use the specified
861 // replay_configuration_ if it has been provided.
862 const Configuration *const base_config = replay_configuration_ == nullptr
863 ? logged_configuration()
864 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800865
866 // Create a config with all the channels, but un-sorted/merged. Collect up
867 // the schemas while we do this. Call MergeConfiguration to sort everything,
868 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800869
870 // This is the builder that we use for the config containing all the new
871 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -0800872 flatbuffers::FlatBufferBuilder fbb;
873 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800874 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -0800875
876 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
877 << ": Merging logic needs to be updated when the number of channel "
878 "fields changes.";
879
880 // List of schemas.
881 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
882 // Make sure our new RemoteMessage schema is in there for old logs without it.
883 schema_map.insert(std::make_pair(
884 RemoteMessage::GetFullyQualifiedName(),
885 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
886 message_bridge::RemoteMessageSchema()))));
887
888 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800889 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -0800890 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800891 base_config, logged_configuration()->channels()->Get(pair.first), "",
892 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -0800893 channel_offsets.emplace_back(
894 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800895 }
Austin Schuh01b4c352020-09-21 23:09:39 -0700896
Austin Schuh0de30f32020-12-06 12:44:28 -0800897 // Now reconstruct the original channels, translating types as needed
898 for (const Channel *c : *base_config->channels()) {
899 // Search for a mapping channel.
900 std::string_view new_type = "";
901 for (auto &pair : remapped_channels_) {
902 const Channel *const remapped_channel =
903 logged_configuration()->channels()->Get(pair.first);
904 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
905 remapped_channel->type()->string_view() == c->type()->string_view()) {
906 new_type = pair.second.new_type;
907 break;
908 }
909 }
910
911 // Copy everything over.
912 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
913
914 // Add the schema if it doesn't exist.
915 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
916 CHECK(c->has_schema());
917 schema_map.insert(std::make_pair(c->type()->string_view(),
918 RecursiveCopyFlatBuffer(c->schema())));
919 }
920 }
921
922 // The MergeConfiguration API takes a vector, not a map. Convert.
923 std::vector<FlatbufferVector<reflection::Schema>> schemas;
924 while (!schema_map.empty()) {
925 schemas.emplace_back(std::move(schema_map.begin()->second));
926 schema_map.erase(schema_map.begin());
927 }
928
929 // Create the Configuration containing the new channels that we want to add.
930 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
931 channels_offset =
932 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
933
934 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -0700935 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -0800936 if (base_config->maps()) {
937 for (const Map *map : *base_config->maps()) {
938 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
939 }
940 }
941
942 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -0700943 for (const MapT &map : maps_) {
944 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -0800945 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -0700946 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -0800947 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -0700948 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -0800949 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -0700950 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
951 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -0800952 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -0700953 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800954 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -0700955 match_builder.add_name(match_name_offset);
956 match_builder.add_type(match_type_offset);
957 if (!map.match->source_node.empty()) {
958 match_builder.add_source_node(match_source_node_offset);
959 }
960 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
961
Austin Schuh0de30f32020-12-06 12:44:28 -0800962 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -0700963 rename_builder.add_name(rename_name_offset);
964 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
965
Austin Schuh0de30f32020-12-06 12:44:28 -0800966 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -0700967 map_builder.add_match(match_offset);
968 map_builder.add_rename(rename_offset);
969 map_offsets.emplace_back(map_builder.Finish());
970 }
971
Austin Schuh0de30f32020-12-06 12:44:28 -0800972 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
973 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -0700974
Austin Schuh0de30f32020-12-06 12:44:28 -0800975 // And copy everything else over.
976 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
977 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
978
979 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
980 applications_offset =
981 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
982
983 // Now insert everything else in unmodified.
984 ConfigurationBuilder configuration_builder(fbb);
985 if (!channels_offset.IsNull()) {
986 configuration_builder.add_channels(channels_offset);
987 }
988 if (!maps_offsets.IsNull()) {
989 configuration_builder.add_maps(maps_offsets);
990 }
991 if (!nodes_offset.IsNull()) {
992 configuration_builder.add_nodes(nodes_offset);
993 }
994 if (!applications_offset.IsNull()) {
995 configuration_builder.add_applications(applications_offset);
996 }
997
998 if (base_config->has_channel_storage_duration()) {
999 configuration_builder.add_channel_storage_duration(
1000 base_config->channel_storage_duration());
1001 }
1002
1003 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1004 << ": Merging logic needs to be updated when the number of configuration "
1005 "fields changes.";
1006
1007 fbb.Finish(configuration_builder.Finish());
1008
1009 // Clean it up and return it! By using MergeConfiguration here, we'll
1010 // actually get a deduplicated config for free too.
1011 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1012 configuration::MergeConfiguration(
1013 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1014
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001015 remapped_configuration_buffer_ =
1016 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001017 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001018
1019 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001020
1021 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001022}
1023
Austin Schuh6f3babe2020-01-26 20:34:50 -08001024const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1025 const Channel *channel) {
1026 std::string_view channel_name = channel->name()->string_view();
1027 std::string_view channel_type = channel->type()->string_view();
1028 const int channel_index =
1029 configuration::ChannelIndex(logged_configuration(), channel);
1030 // If the channel is remapped, find the correct channel name to use.
1031 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001032 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001033 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001034 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001035 }
1036
Austin Schuhee711052020-08-24 16:06:09 -07001037 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001038 const Channel *remapped_channel = configuration::GetChannel(
1039 event_loop->configuration(), channel_name, channel_type,
1040 event_loop->name(), event_loop->node());
1041
1042 CHECK(remapped_channel != nullptr)
1043 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1044 << channel_type << "\"} because it is not in the provided configuration.";
1045
1046 return remapped_channel;
1047}
1048
Austin Schuh287d43d2020-12-04 20:19:33 -08001049LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1050 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1051
1052void LogReader::State::AddPeer(State *peer) {
1053 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1054 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1055 }
1056}
Austin Schuh858c9f32020-08-31 16:56:12 -07001057
1058EventLoop *LogReader::State::SetNodeEventLoopFactory(
1059 NodeEventLoopFactory *node_event_loop_factory) {
1060 node_event_loop_factory_ = node_event_loop_factory;
1061 event_loop_unique_ptr_ =
1062 node_event_loop_factory_->MakeEventLoop("log_reader");
1063 return event_loop_unique_ptr_.get();
1064}
1065
1066void LogReader::State::SetChannelCount(size_t count) {
1067 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001068 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001069 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001070 channel_source_state_.resize(count);
1071 factory_channel_index_.resize(count);
1072 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001073}
1074
1075void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001076 size_t logged_channel_index, size_t factory_channel_index,
1077 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001078 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001079 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001080 channels_[logged_channel_index] = std::move(sender);
1081 filters_[logged_channel_index] = filter;
1082 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1083
1084 if (source_state) {
1085 channel_source_state_[logged_channel_index] = source_state;
1086
1087 if (remote_timestamp_sender != nullptr) {
1088 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001089 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001090 }
1091 }
1092
1093 factory_channel_index_[logged_channel_index] = factory_channel_index;
1094}
1095
Austin Schuh287d43d2020-12-04 20:19:33 -08001096bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1097 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001098 uint32_t remote_queue_index = 0xffffffff;
1099
Austin Schuh287d43d2020-12-04 20:19:33 -08001100 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001101 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001102 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1103 ->queue_index_map_[timestamped_message.channel_index]
1104 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001105
Austin Schuh9942bae2021-01-07 22:06:44 -08001106 struct SentTimestamp {
1107 monotonic_clock::time_point monotonic_event_time;
1108 uint32_t queue_index;
1109 } search;
1110
Austin Schuh287d43d2020-12-04 20:19:33 -08001111 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001112 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001113
1114 // Find the sent time if available.
1115 auto element = std::lower_bound(
1116 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001117 [](ContiguousSentTimestamp a, SentTimestamp b) {
1118 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001119 return true;
1120 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001121 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001122 return false;
1123 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001124
1125 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001126 return true;
1127 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001128 if (a.starting_queue_index >= b.queue_index) {
1129 return false;
1130 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001131
Austin Schuh9942bae2021-01-07 22:06:44 -08001132 // If it isn't clearly below or above, it is below. Since we return
1133 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001134 return false;
1135 });
1136
1137 // TODO(austin): Be a bit more principled here, but we will want to do that
1138 // after the logger rewrite. We hit this when one node finishes, but the
1139 // other node isn't done yet. So there is no send time, but there is a
1140 // receive time.
1141 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001142 CHECK_GE(timestamped_message.monotonic_remote_time,
1143 element->starting_monotonic_event_time);
1144 CHECK_LE(timestamped_message.monotonic_remote_time,
1145 element->ending_monotonic_event_time);
1146 CHECK_GE(timestamped_message.remote_queue_index,
1147 element->starting_queue_index);
1148 CHECK_LE(timestamped_message.remote_queue_index,
1149 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001150
Austin Schuh9942bae2021-01-07 22:06:44 -08001151 remote_queue_index = timestamped_message.remote_queue_index +
1152 element->actual_queue_index -
1153 element->starting_queue_index;
1154 } else {
1155 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001156 }
1157 }
1158
1159 // Send! Use the replayed queue index here instead of the logged queue index
1160 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001161 const bool sent = sender->Send(
1162 timestamped_message.data.message().data()->Data(),
1163 timestamped_message.data.message().data()->size(),
1164 timestamped_message.monotonic_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001165 timestamped_message.realtime_remote_time, remote_queue_index,
1166 (channel_source_state_[timestamped_message.channel_index] != nullptr
1167 ? CHECK_NOTNULL(
1168 channel_source_state_[timestamped_message.channel_index])
1169 ->event_loop_->boot_uuid()
1170 : event_loop_->boot_uuid()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001171 if (!sent) return false;
1172
Austin Schuh287d43d2020-12-04 20:19:33 -08001173 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001174 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1175 // Nothing here, start a range with 0 length.
1176 ContiguousSentTimestamp timestamp;
1177 timestamp.starting_monotonic_event_time =
1178 timestamp.ending_monotonic_event_time =
1179 timestamped_message.monotonic_event_time;
1180 timestamp.starting_queue_index = timestamp.ending_queue_index =
1181 timestamped_message.queue_index;
1182 timestamp.actual_queue_index = sender->sent_queue_index();
1183 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1184 timestamp);
1185 } else {
1186 // We've got something. See if the next timestamp is still contiguous. If
1187 // so, grow it.
1188 ContiguousSentTimestamp *back =
1189 &queue_index_map_[timestamped_message.channel_index]->back();
1190 if ((back->starting_queue_index - back->actual_queue_index) ==
1191 (timestamped_message.queue_index - sender->sent_queue_index())) {
1192 back->ending_queue_index = timestamped_message.queue_index;
1193 back->ending_monotonic_event_time =
1194 timestamped_message.monotonic_event_time;
1195 } else {
1196 // Otherwise, make a new one.
1197 ContiguousSentTimestamp timestamp;
1198 timestamp.starting_monotonic_event_time =
1199 timestamp.ending_monotonic_event_time =
1200 timestamped_message.monotonic_event_time;
1201 timestamp.starting_queue_index = timestamp.ending_queue_index =
1202 timestamped_message.queue_index;
1203 timestamp.actual_queue_index = sender->sent_queue_index();
1204 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1205 timestamp);
1206 }
1207 }
1208
1209 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1210 // queue index diverge a couple of elements, which would be a very small
1211 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001212 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1213 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001214 flatbuffers::FlatBufferBuilder fbb;
1215 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001216 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1217 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001218
Austin Schuh969cd602021-01-03 00:09:45 -08001219 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001220
1221 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001222 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001223
1224 // Swap the remote and sent metrics. They are from the sender's
1225 // perspective, not the receiver's perspective.
1226 message_header_builder.add_monotonic_sent_time(
1227 sender->monotonic_sent_time().time_since_epoch().count());
1228 message_header_builder.add_realtime_sent_time(
1229 sender->realtime_sent_time().time_since_epoch().count());
1230 message_header_builder.add_queue_index(sender->sent_queue_index());
1231
1232 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001233 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001234 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001235 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001236
1237 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001238 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001239
Austin Schuh969cd602021-01-03 00:09:45 -08001240 fbb.Finish(message_header_builder.Finish());
1241
1242 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1243 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
1244 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001245 }
1246
1247 return true;
1248}
1249
Austin Schuh969cd602021-01-03 00:09:45 -08001250LogReader::RemoteMessageSender::RemoteMessageSender(
1251 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1252 : event_loop_(event_loop),
1253 sender_(std::move(sender)),
1254 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1255
1256void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1257 if (remote_timestamps_.empty()) {
1258 CHECK_NOTNULL(timer_);
1259 timer_->Disable();
1260 scheduled_time_ = monotonic_clock::min_time;
1261 return;
1262 }
1263
1264 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1265 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001266 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001267 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001268 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1269 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001270 }
1271}
1272
1273void LogReader::RemoteMessageSender::Send(
1274 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
1275 monotonic_clock::time_point monotonic_timestamp_time) {
1276 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
1277 // resend the timestamp at the correct time, or we don't and can send it
1278 // immediately.
1279 if (monotonic_timestamp_time == monotonic_clock::min_time) {
1280 CHECK(remote_timestamps_.empty())
1281 << ": Unsupported mix of timestamps and no timestamps.";
1282 sender_.Send(std::move(remote_message));
1283 } else {
Austin Schuhb22ae422021-01-31 17:57:06 -08001284 remote_timestamps_.emplace(
1285 std::upper_bound(
1286 remote_timestamps_.begin(), remote_timestamps_.end(),
1287 monotonic_timestamp_time,
1288 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1289 const Timestamp &timestamp) {
1290 return monotonic_timestamp_time <
1291 timestamp.monotonic_timestamp_time;
1292 }),
1293 std::move(remote_message), monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001294 ScheduleTimestamp();
1295 }
1296}
1297
1298void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001299 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1300 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001301 CHECK(!remote_timestamps_.empty());
1302
1303 // Send out all timestamps at the currently scheduled time.
1304 while (remote_timestamps_.front().monotonic_timestamp_time ==
1305 scheduled_time_) {
1306 sender_.Send(std::move(remote_timestamps_.front().remote_message));
1307 remote_timestamps_.pop_front();
1308 if (remote_timestamps_.empty()) {
1309 break;
1310 }
1311 }
1312 scheduled_time_ = monotonic_clock::min_time;
1313
1314 ScheduleTimestamp();
1315}
1316
1317LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001318 const Channel *channel, const Connection *connection) {
1319 message_bridge::ChannelTimestampFinder finder(event_loop_);
1320 // Look at any pre-created channel/connection pairs.
1321 {
1322 auto it =
1323 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1324 if (it != channel_timestamp_loggers_.end()) {
1325 return it->second.get();
1326 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001327 }
1328
Austin Schuh61e973f2021-02-21 21:43:56 -08001329 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1330 // to.
1331 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1332
1333 {
1334 // See if that has been created before. If so, cache it in
1335 // channel_timestamp_loggers_ and return.
1336 auto it = timestamp_loggers_.find(timestamp_channel);
1337 if (it != timestamp_loggers_.end()) {
1338 CHECK(channel_timestamp_loggers_
1339 .try_emplace(std::make_pair(channel, connection), it->second)
1340 .second);
1341 return it->second.get();
1342 }
1343 }
1344
1345 // Otherwise, make a sender, save it, and cache it.
1346 auto result = channel_timestamp_loggers_.try_emplace(
1347 std::make_pair(channel, connection),
1348 std::make_shared<RemoteMessageSender>(
1349 event_loop()->MakeSender<RemoteMessage>(
1350 timestamp_channel->name()->string_view()),
1351 event_loop()));
1352
1353 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1354 .second);
1355 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001356}
1357
Austin Schuhdda74ec2021-01-03 19:30:37 -08001358TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001359 CHECK(timestamp_mapper_ != nullptr);
1360 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1361 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001362
Austin Schuhe639ea12021-01-25 13:00:22 -08001363 TimestampedMessage result = std::move(*result_ptr);
1364
Austin Schuh2f8fd752020-09-01 22:38:28 -07001365 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001366 << result.monotonic_event_time;
1367 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001368 SeedSortedMessages();
1369
Austin Schuhe639ea12021-01-25 13:00:22 -08001370 if (result.monotonic_remote_time != monotonic_clock::min_time) {
1371 message_bridge::NoncausalOffsetEstimator *filter =
1372 filters_[result.channel_index];
1373 CHECK(filter != nullptr);
1374
1375 // TODO(austin): We probably want to push this down into the timestamp
1376 // mapper directly.
Austin Schuh3d94be02021-02-12 23:15:20 -08001377 filter->Pop(event_loop_->node(), event_loop_->monotonic_now());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 }
Austin Schuh5ee56872021-01-30 16:53:34 -08001379 VLOG(1) << "Popped " << result
1380 << configuration::CleanedChannelToString(
1381 event_loop_->configuration()->channels()->Get(
1382 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001383 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001384}
1385
1386monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
Austin Schuhe639ea12021-01-25 13:00:22 -08001387 if (timestamp_mapper_ == nullptr) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001388 return monotonic_clock::max_time;
1389 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001390 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1391 if (result_ptr == nullptr) {
1392 return monotonic_clock::max_time;
1393 }
1394 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
1395 << result_ptr->monotonic_event_time;
1396 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001397}
1398
1399void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001400 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001401
Austin Schuhe639ea12021-01-25 13:00:22 -08001402 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1403 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001404}
1405
1406void LogReader::State::Deregister() {
1407 for (size_t i = 0; i < channels_.size(); ++i) {
1408 channels_[i].reset();
1409 }
Austin Schuh61e973f2021-02-21 21:43:56 -08001410 channel_timestamp_loggers_.clear();
1411 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001412 event_loop_unique_ptr_.reset();
1413 event_loop_ = nullptr;
1414 timer_handler_ = nullptr;
1415 node_event_loop_factory_ = nullptr;
1416}
1417
Austin Schuhe309d2a2019-11-29 13:25:21 -08001418} // namespace logger
1419} // namespace aos