blob: e295fc1fbeae936f66b9146d557262238d0ed390 [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 {
Austin Schuh006a9f52021-04-07 16:24:18 -070042namespace configuration {
43// We don't really want to expose this publicly, but log reader doesn't really
44// want to re-implement it.
45void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
46 std::string *name, std::string_view type, const Node *node);
47}
Austin Schuhe309d2a2019-11-29 13:25:21 -080048namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070049namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080050
Austin Schuh315b96b2020-12-11 21:21:12 -080051std::string LogFileVectorToString(std::vector<LogFile> log_files) {
52 std::stringstream ss;
Austin Schuh297d2352021-01-21 19:02:17 -080053 for (const auto &f : log_files) {
Austin Schuh315b96b2020-12-11 21:21:12 -080054 ss << f << "\n";
55 }
56 return ss.str();
57}
58
Austin Schuh0de30f32020-12-06 12:44:28 -080059// Copies the channel, removing the schema as we go. If new_name is provided,
60// it is used instead of the name inside the channel. If new_type is provided,
61// it is used instead of the type in the channel.
62flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
63 std::string_view new_name,
64 std::string_view new_type,
65 flatbuffers::FlatBufferBuilder *fbb) {
66 flatbuffers::Offset<flatbuffers::String> name_offset =
67 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
68 : new_name);
69 flatbuffers::Offset<flatbuffers::String> type_offset =
70 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
71 flatbuffers::Offset<flatbuffers::String> source_node_offset =
72 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
73 : 0;
74
75 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
76 destination_nodes_offset =
77 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
78
79 flatbuffers::Offset<
80 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
81 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
82
83 Channel::Builder channel_builder(*fbb);
84 channel_builder.add_name(name_offset);
85 channel_builder.add_type(type_offset);
86 if (c->has_frequency()) {
87 channel_builder.add_frequency(c->frequency());
88 }
89 if (c->has_max_size()) {
90 channel_builder.add_max_size(c->max_size());
91 }
92 if (c->has_num_senders()) {
93 channel_builder.add_num_senders(c->num_senders());
94 }
95 if (c->has_num_watchers()) {
96 channel_builder.add_num_watchers(c->num_watchers());
97 }
98 if (!source_node_offset.IsNull()) {
99 channel_builder.add_source_node(source_node_offset);
100 }
101 if (!destination_nodes_offset.IsNull()) {
102 channel_builder.add_destination_nodes(destination_nodes_offset);
103 }
104 if (c->has_logger()) {
105 channel_builder.add_logger(c->logger());
106 }
107 if (!logger_nodes_offset.IsNull()) {
108 channel_builder.add_logger_nodes(logger_nodes_offset);
109 }
110 if (c->has_read_method()) {
111 channel_builder.add_read_method(c->read_method());
112 }
113 if (c->has_num_readers()) {
114 channel_builder.add_num_readers(c->num_readers());
115 }
116 return channel_builder.Finish();
117}
118
Austin Schuhe309d2a2019-11-29 13:25:21 -0800119namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800120using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700121} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800122
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800123LogReader::LogReader(std::string_view filename,
124 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800125 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800126
Austin Schuh287d43d2020-12-04 20:19:33 -0800127LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800128 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800129 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800130 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800131 CHECK_GT(log_files_.size(), 0u);
132 {
133 // Validate that we have the same config everwhere. This will be true if
134 // all the parts were sorted together and the configs match.
135 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800136 for (const LogFile &log_file : log_files_) {
137 if (log_file.config.get() == nullptr) {
138 LOG(FATAL) << "Couldn't find a config in " << log_file;
139 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800140 if (config == nullptr) {
141 config = log_file.config.get();
142 } else {
143 CHECK_EQ(config, log_file.config.get());
144 }
145 }
146 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800147
Austin Schuh6331ef92020-01-07 18:28:09 -0800148 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800149
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700150 // Remap all existing remote timestamp channels. They will be recreated, and
151 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700152 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800153 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
154 "log_reader", node);
155
156 absl::btree_set<std::string_view> remote_nodes;
157
158 for (const Channel *channel : *logged_configuration()->channels()) {
159 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
160 continue;
161 }
162 if (!channel->has_destination_nodes()) {
163 continue;
164 }
165 for (const Connection *connection : *channel->destination_nodes()) {
166 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
167 node)) {
168 // Start by seeing if the split timestamp channels are being used for
169 // this message. If so, remap them.
170 const Channel *timestamp_channel = configuration::GetChannel(
171 logged_configuration(),
172 finder.SplitChannelName(channel, connection),
173 RemoteMessage::GetFullyQualifiedName(), "", node, true);
174
175 if (timestamp_channel != nullptr) {
176 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
177 RemapLoggedChannel<RemoteMessage>(
178 timestamp_channel->name()->string_view(), node);
179 }
180 continue;
181 }
182
183 // Otherwise collect this one up as a node to look for a combined
184 // channel from. It is more efficient to compare nodes than channels.
185 remote_nodes.insert(connection->name()->string_view());
186 }
187 }
188 }
189
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700190 std::vector<const Node *> timestamp_logger_nodes =
191 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800192 for (const std::string_view remote_node : remote_nodes) {
193 const std::string channel = finder.CombinedChannelName(remote_node);
194
Austin Schuh0de30f32020-12-06 12:44:28 -0800195 // See if the log file is an old log with MessageHeader channels in it, or
196 // a newer log with RemoteMessage. If we find an older log, rename the
197 // type too along with the name.
198 if (HasChannel<MessageHeader>(channel, node)) {
199 CHECK(!HasChannel<RemoteMessage>(channel, node))
200 << ": Can't have both a MessageHeader and RemoteMessage remote "
201 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800202 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
203 // careful about updating the config, but there are fewer and fewer logs
204 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800205 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
206 "aos.message_bridge.RemoteMessage");
207 } else {
208 CHECK(HasChannel<RemoteMessage>(channel, node))
209 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
210 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
211 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800212 // Only bother to remap if there's something on the channel. We can
213 // tell if the channel was marked NOT_LOGGED or not. This makes the
214 // config not change un-necesarily when we replay a log with NOT_LOGGED
215 // messages.
216 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
217 RemapLoggedChannel<RemoteMessage>(channel, node);
218 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800219 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700220 }
221 }
222
Austin Schuh6aa77be2020-02-22 21:06:40 -0800223 if (replay_configuration) {
224 CHECK_EQ(configuration::MultiNode(configuration()),
225 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700226 << ": Log file and replay config need to both be multi or single "
227 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800228 }
229
Austin Schuh6f3babe2020-01-26 20:34:50 -0800230 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800231 states_.emplace_back(std::make_unique<State>(
232 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800233 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800234 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700235 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800236 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700237 << ": Log file and replay config need to have matching nodes "
238 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700239 for (const Node *node : *logged_configuration()->nodes()) {
240 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700241 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
242 << " in logged config that is not present in the replay "
243 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700244 }
245 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800246 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800247 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800248 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800249}
250
Austin Schuh6aa77be2020-02-22 21:06:40 -0800251LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700252 if (event_loop_factory_unique_ptr_) {
253 Deregister();
254 } else if (event_loop_factory_ != nullptr) {
255 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
256 "is destroyed";
257 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700258 // Zero out some buffers. It's easy to do use-after-frees on these, so make
259 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700260 if (remapped_configuration_buffer_) {
261 remapped_configuration_buffer_->Wipe();
262 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800263}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800264
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800265const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800266 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800267}
268
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800269const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800270 return remapped_configuration_;
271}
272
Austin Schuh07676622021-01-21 18:59:17 -0800273std::vector<const Node *> LogReader::LoggedNodes() const {
274 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800275}
Austin Schuh15649d62019-12-28 16:36:38 -0800276
Austin Schuh11d43732020-09-21 17:28:30 -0700277monotonic_clock::time_point LogReader::monotonic_start_time(
278 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800279 State *state =
280 states_[configuration::GetNodeIndex(configuration(), node)].get();
281 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
282
Austin Schuh858c9f32020-08-31 16:56:12 -0700283 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800284}
285
Austin Schuh11d43732020-09-21 17:28:30 -0700286realtime_clock::time_point LogReader::realtime_start_time(
287 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800288 State *state =
289 states_[configuration::GetNodeIndex(configuration(), node)].get();
290 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
291
Austin Schuh858c9f32020-08-31 16:56:12 -0700292 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800293}
294
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800295void LogReader::Register() {
296 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800297 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800298 Register(event_loop_factory_unique_ptr_.get());
299}
300
Austin Schuh92547522019-12-28 14:33:43 -0800301void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800302 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700303 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800304 filters_ =
305 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800306 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuhfe3fb342021-01-16 18:50:37 -0800307 FLAGS_skip_order_validation,
308 chrono::duration_cast<chrono::nanoseconds>(
309 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800310
Austin Schuhe639ea12021-01-25 13:00:22 -0800311 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700312 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800313 const size_t node_index =
314 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800315 std::vector<LogParts> filtered_parts = FilterPartsForNode(
316 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800317
318 // Confirm that all the parts are from the same boot if there are enough
319 // parts to not be from the same boot.
320 if (filtered_parts.size() > 1u) {
321 for (size_t i = 1; i < filtered_parts.size(); ++i) {
322 CHECK_EQ(filtered_parts[i].source_boot_uuid,
323 filtered_parts[0].source_boot_uuid)
Austin Schuh8902fa52021-03-14 22:39:24 -0700324 << ": Found parts from different boots for node "
325 << node->name()->string_view() << " "
Austin Schuh315b96b2020-12-11 21:21:12 -0800326 << LogFileVectorToString(log_files_);
327 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800328 if (!filtered_parts[0].source_boot_uuid.empty()) {
329 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
330 filtered_parts[0].source_boot_uuid);
331 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800332 }
333
Austin Schuh287d43d2020-12-04 20:19:33 -0800334 states_[node_index] = std::make_unique<State>(
335 filtered_parts.size() == 0u
336 ? nullptr
337 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800338 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700339 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700340 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700341
342 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800343 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800344 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800345 filters_->SetTimestampMappers(std::move(timestamp_mappers));
346
347 // Note: this needs to be set before any times are pulled, or we won't observe
348 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800349 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700350
Austin Schuh287d43d2020-12-04 20:19:33 -0800351 for (const Node *node : configuration::GetNodes(configuration())) {
352 const size_t node_index =
353 configuration::GetNodeIndex(configuration(), node);
354 State *state = states_[node_index].get();
355 for (const Node *other_node : configuration::GetNodes(configuration())) {
356 const size_t other_node_index =
357 configuration::GetNodeIndex(configuration(), other_node);
358 State *other_state = states_[other_node_index].get();
359 if (other_state != state) {
360 state->AddPeer(other_state);
361 }
362 }
363 }
364
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700365 // Register after making all the State objects so we can build references
366 // between them.
367 for (const Node *node : configuration::GetNodes(configuration())) {
368 const size_t node_index =
369 configuration::GetNodeIndex(configuration(), node);
370 State *state = states_[node_index].get();
371
372 Register(state->event_loop());
373 }
374
James Kuszmaul46d82582020-05-09 19:50:09 -0700375 if (live_nodes_ == 0) {
376 LOG(FATAL)
377 << "Don't have logs from any of the nodes in the replay config--are "
378 "you sure that the replay config matches the original config?";
379 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800380
Austin Schuh87dd3832021-01-01 23:07:31 -0800381 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800382
Austin Schuh858c9f32020-08-31 16:56:12 -0700383 for (std::unique_ptr<State> &state : states_) {
384 state->SeedSortedMessages();
385 }
386
Austin Schuh2f8fd752020-09-01 22:38:28 -0700387 // We want to start the log file at the last start time of the log files
388 // from all the nodes. Compute how long each node's simulation needs to run
389 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800390 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800391
Austin Schuh2f8fd752020-09-01 22:38:28 -0700392 // TODO(austin): We want an "OnStart" callback for each node rather than
393 // running until the last node.
394
Austin Schuh8bd96322020-02-13 21:18:22 -0800395 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700396 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
397 << MaybeNodeName(state->event_loop()->node()) << "now "
398 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -0800399 if (state->monotonic_start_time() == monotonic_clock::min_time) {
400 continue;
401 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700402 // And start computing the start time on the distributed clock now that
403 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -0700404 start_time = std::max(
405 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -0800406 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700407
Austin Schuh87dd3832021-01-01 23:07:31 -0800408 // TODO(austin): If a node doesn't have a start time, we might not queue
409 // enough. If this happens, we'll explode with a frozen error eventually.
410
Austin Schuh2f8fd752020-09-01 22:38:28 -0700411 CHECK_GE(start_time, distributed_clock::epoch())
412 << ": Hmm, we have a node starting before the start of time. Offset "
413 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -0800414
Austin Schuh6f3babe2020-01-26 20:34:50 -0800415 // Forwarding is tracked per channel. If it is enabled, we want to turn it
416 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700417 // nodes, and also replayed on the other nodes. This may not satisfy all
418 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800419 if (configuration::MultiNode(event_loop_factory_->configuration())) {
420 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
421 const Channel *channel = logged_configuration()->channels()->Get(i);
422 const Node *node = configuration::GetNode(
423 configuration(), channel->source_node()->string_view());
424
Austin Schuh8bd96322020-02-13 21:18:22 -0800425 State *state =
426 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800427
428 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -0700429 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800430
431 event_loop_factory_->DisableForwarding(remapped_channel);
432 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700433
434 // If we are replaying a log, we don't want a bunch of redundant messages
435 // from both the real message bridge and simulated message bridge.
436 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800437 }
438
Austin Schuhcde938c2020-02-02 17:30:07 -0800439 // While we are starting the system up, we might be relying on matching data
440 // to timestamps on log files where the timestamp log file starts before the
441 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800442 {
443 const bool prior_ignore_missing_data = ignore_missing_data_;
444 ignore_missing_data_ = true;
445 VLOG(1) << "Running until " << start_time << " in Register";
446 event_loop_factory_->RunFor(start_time.time_since_epoch());
447 VLOG(1) << "At start time";
448 // Now that we are running for real, missing data means that the log file is
449 // corrupted or went wrong.
450 ignore_missing_data_ = prior_ignore_missing_data;
451 }
Austin Schuh92547522019-12-28 14:33:43 -0800452
Austin Schuh8bd96322020-02-13 21:18:22 -0800453 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700454 // Make the RT clock be correct before handing it to the user.
455 if (state->realtime_start_time() != realtime_clock::min_time) {
456 state->SetRealtimeOffset(state->monotonic_start_time(),
457 state->realtime_start_time());
458 }
459 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
460 << MaybeNodeName(state->event_loop()->node()) << "now "
461 << state->monotonic_now();
462 }
463
464 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800465 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800466 }
467}
468
Austin Schuh2f8fd752020-09-01 22:38:28 -0700469message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800470 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800471 if (filters_) {
472 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800473 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800474 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800475}
476
Austin Schuhe309d2a2019-11-29 13:25:21 -0800477void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800478 State *state =
479 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
480 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800481
Austin Schuh858c9f32020-08-31 16:56:12 -0700482 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800483
Tyler Chatow67ddb032020-01-12 14:30:04 -0800484 // We don't run timing reports when trying to print out logged data, because
485 // otherwise we would end up printing out the timing reports themselves...
486 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800487 event_loop->SkipTimingReport();
488 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -0800489
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700490 for (size_t logged_channel_index = 0;
491 logged_channel_index < logged_configuration()->channels()->size();
492 ++logged_channel_index) {
493 const Channel *channel = RemapChannel(
494 event_loop,
495 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800496
Austin Schuh532656d2021-01-11 10:17:18 -0800497 if (channel->logger() == LoggerConfig::NOT_LOGGED) {
498 continue;
499 }
500
Austin Schuh2f8fd752020-09-01 22:38:28 -0700501 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -0800502 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700503
504 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800505
506 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
507 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700508 // We've got a message which is being forwarded to this node.
509 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -0800510 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700511 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800512
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700513 // Delivery timestamps are supposed to be logged back on the source node.
514 // Configure remote timestamps to be sent.
Austin Schuh61e973f2021-02-21 21:43:56 -0800515 const Connection *connection =
516 configuration::ConnectionToNode(channel, event_loop->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700517 const bool delivery_time_is_logged =
Austin Schuh61e973f2021-02-21 21:43:56 -0800518 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
519 source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700520
521 source_state =
522 states_[configuration::GetNodeIndex(configuration(), source_node)]
523 .get();
524
525 if (delivery_time_is_logged) {
526 remote_timestamp_sender =
Austin Schuh61e973f2021-02-21 21:43:56 -0800527 source_state->RemoteTimestampSender(channel, connection);
Austin Schuh8bd96322020-02-13 21:18:22 -0800528 }
529 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700530
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700531 state->SetChannel(
532 logged_channel_index,
533 configuration::ChannelIndex(event_loop->configuration(), channel),
534 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
535 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800536 }
537
Austin Schuh6aa77be2020-02-22 21:06:40 -0800538 // If we didn't find any log files with data in them, we won't ever get a
539 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -0800540 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800541 return;
542 }
543
Austin Schuh858c9f32020-08-31 16:56:12 -0700544 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700545 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
546 << "at " << state->event_loop()->context().monotonic_event_time
547 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700548 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800549 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700550 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800551 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800552 event_loop_factory_->Exit();
553 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800554 return;
555 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700556
Austin Schuhdda74ec2021-01-03 19:30:37 -0800557 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -0800558
Austin Schuhe309d2a2019-11-29 13:25:21 -0800559 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700560 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700561 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800562 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700563 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
564 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800565 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700566 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -0800567 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700568 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800569 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700570 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800571 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700572 << "): " << FlatbufferToJson(state->event_loop()->node())
573 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800574 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700575 << state->DebugString();
576 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800577
Austin Schuh287d43d2020-12-04 20:19:33 -0800578 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -0700579 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -0800580 event_loop_factory_ != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800581 if (timestamped_message.data.span().size() != 0u) {
582 if (timestamped_message.monotonic_remote_time !=
583 monotonic_clock::min_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800584 // Confirm that the message was sent on the sending node before the
585 // destination node (this node). As a proxy, do this by making sure
586 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800587 //
588 // TODO(austin): <= means that the cause message (which we know) could
589 // happen after the effect even though we know they are at the same
590 // time. I doubt anyone will notice for a bit, but we should really
591 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700592 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800593 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -0800594 timestamped_message.monotonic_remote_time,
595 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700596 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800597 << state->remote_node(timestamped_message.channel_index)
598 ->name()
599 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800600 << " while trying to send a message on "
601 << configuration::CleanedChannelToString(
602 logged_configuration()->channels()->Get(
603 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700604 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -0800605 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -0800606 state->monotonic_remote_now(
607 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700608 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800609 << "Check failed: timestamped_message.monotonic_remote_time < "
610 "state->monotonic_remote_now(timestamped_message.channel_"
611 "index) ("
612 << timestamped_message.monotonic_remote_time << " vs. "
613 << state->monotonic_remote_now(
614 timestamped_message.channel_index)
615 << ") " << state->event_loop()->node()->name()->string_view()
616 << " to "
617 << state->remote_node(timestamped_message.channel_index)
618 ->name()
619 ->string_view()
620 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700621 << " ("
622 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800623 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700624 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800625 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700626 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800627 timestamped_message.channel_index,
628 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700629 << ") " << state->DebugString();
630 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800631 }
632
Austin Schuh15649d62019-12-28 16:36:38 -0800633 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -0800634 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
635 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800636
Austin Schuh2f8fd752020-09-01 22:38:28 -0700637 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800638 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700639 // TODO(austin): std::move channel_data in and make that efficient in
640 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800641 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800642 } else if (!ignore_missing_data_ &&
Austin Schuh5ee56872021-01-30 16:53:34 -0800643 // When starting up, we can have data which was sent before the
644 // log starts, but the timestamp was after the log starts. This
645 // is unreasonable to avoid, so ignore the missing data.
646 timestamped_message.monotonic_remote_time >=
647 state->monotonic_remote_start_time(
648 timestamped_message.channel_index) &&
Austin Schuhdda74ec2021-01-03 19:30:37 -0800649 !FLAGS_skip_missing_forwarding_entries) {
Austin Schuh5ee56872021-01-30 16:53:34 -0800650 // We've found a timestamp without data that we expect to have data for.
651 // This likely means that we are at the end of the log file. Record it
652 // and CHECK that in the rest of the log file, we don't find any more
653 // data on that channel. Not all channels will end at the same point in
654 // time since they can be in different files.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800655 VLOG(1) << "Found the last message on channel "
Austin Schuh94526302021-04-28 22:46:34 -0700656 << timestamped_message.channel_index << ", "
657 << configuration::CleanedChannelToString(
658 logged_configuration()->channels()->Get(
659 timestamped_message.channel_index));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800660
Austin Schuh2bb80e02021-03-20 21:46:17 -0700661 // The user might be working with log files from 1 node but forgot to
662 // configure the infrastructure to log data for a remote channel on that
663 // node. That can be very hard to debug, even though the log reader is
664 // doing the right thing. At least log a warning in that case and tell
665 // the user what is happening so they can either update their config to
666 // log the channel or can find a log with the data.
667 {
668 const std::vector<std::string> logger_nodes =
669 FindLoggerNodes(log_files_);
670 if (logger_nodes.size()) {
671 // We have old logs which don't have the logger nodes logged. In
672 // that case, we can't be helpful :(
673 bool data_logged = false;
674 const Channel *channel = logged_configuration()->channels()->Get(
675 timestamped_message.channel_index);
676 for (const std::string &node : logger_nodes) {
677 data_logged |=
678 configuration::ChannelMessageIsLoggedOnNode(channel, node);
679 }
680 if (!data_logged) {
681 LOG(WARNING) << "Got a timestamp without any logfiles which "
682 "could contain data for channel "
683 << configuration::CleanedChannelToString(channel);
684 LOG(WARNING) << "Only have logs logged on ["
685 << absl::StrJoin(logger_nodes, ", ") << "]";
686 LOG(WARNING)
687 << "Dropping the rest of the data on "
688 << state->event_loop()->node()->name()->string_view();
689 LOG(WARNING)
690 << "Consider using --skip_missing_forwarding_entries to "
691 "bypass this, update your config to log it, or add data "
692 "from one of the nodes it is logged on.";
693 }
694 }
695 }
696
Austin Schuhdda74ec2021-01-03 19:30:37 -0800697 // Vector storing if we've seen a nullptr message or not per channel.
698 std::vector<bool> last_message;
699 last_message.resize(logged_configuration()->channels()->size(), false);
700
701 last_message[timestamped_message.channel_index] = true;
702
703 // Now that we found the end of one channel, artificially stop the
704 // rest. It is confusing when part of your data gets replayed but not
Austin Schuh5ee56872021-01-30 16:53:34 -0800705 // all. Read the rest of the messages and drop them on the floor while
706 // doing some basic validation.
Austin Schuh858c9f32020-08-31 16:56:12 -0700707 while (state->OldestMessageTime() != monotonic_clock::max_time) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800708 TimestampedMessage next = state->PopOldest();
709 // Make sure that once we have seen the last message on a channel,
710 // data doesn't start back up again. If the user wants to play
711 // through events like this, they can set
712 // --skip_missing_forwarding_entries or ignore_missing_data_.
713 CHECK_LT(next.channel_index, last_message.size());
714 if (next.data.span().size() == 0u) {
715 last_message[next.channel_index] = true;
716 } else {
717 if (last_message[next.channel_index]) {
718 LOG(FATAL)
719 << "Found missing data in the middle of the log file on "
720 "channel "
721 << next.channel_index << " Last "
722 << last_message[next.channel_index] << state->DebugString();
723 }
724 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800725 }
Austin Schuh92547522019-12-28 14:33:43 -0800726 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800727 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800728 LOG(WARNING)
729 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800730 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -0800731 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -0700732 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -0800733 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -0700734 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -0800735 }
736
Austin Schuh858c9f32020-08-31 16:56:12 -0700737 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800738 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700739 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
740 << "wakeup for " << next_time << "("
741 << state->ToDistributedClock(next_time)
742 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700743 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -0800744 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700745 VLOG(1) << MaybeNodeName(state->event_loop()->node())
746 << "No next message, scheduling shutdown";
747 // Set a timer up immediately after now to die. If we don't do this,
748 // then the senders waiting on the message we just read will never get
749 // called.
Austin Schuheecb9282020-01-08 17:43:30 -0800750 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700751 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
752 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -0800753 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800754 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800755
Austin Schuh2f8fd752020-09-01 22:38:28 -0700756 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
757 << state->event_loop()->context().monotonic_event_time << " now "
758 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700759 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800760
Austin Schuh6f3babe2020-01-26 20:34:50 -0800761 ++live_nodes_;
762
Austin Schuh858c9f32020-08-31 16:56:12 -0700763 if (state->OldestMessageTime() != monotonic_clock::max_time) {
764 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -0800765 }
766}
767
768void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800769 // Make sure that things get destroyed in the correct order, rather than
770 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -0800771 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700772 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800773 }
Austin Schuh92547522019-12-28 14:33:43 -0800774
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800775 event_loop_factory_unique_ptr_.reset();
776 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800777}
778
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800779void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800780 std::string_view add_prefix,
781 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800782 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
783 const Channel *const channel = logged_configuration()->channels()->Get(ii);
784 if (channel->name()->str() == name &&
785 channel->type()->string_view() == type) {
786 CHECK_EQ(0u, remapped_channels_.count(ii))
787 << "Already remapped channel "
788 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800789 RemappedChannel remapped_channel;
790 remapped_channel.remapped_name =
791 std::string(add_prefix) + std::string(name);
792 remapped_channel.new_type = new_type;
793 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800794 VLOG(1) << "Remapping channel "
795 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -0800796 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -0800797 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800798 return;
799 }
800 }
801 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
802 << type;
803}
804
Austin Schuh01b4c352020-09-21 23:09:39 -0700805void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
806 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800807 std::string_view add_prefix,
808 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -0700809 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
810 const Channel *remapped_channel =
811 configuration::GetChannel(logged_configuration(), name, type, "", node);
812 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
813 << "\", \"type\": \"" << type << "\"}";
814 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
815 << "\"}";
816 VLOG(1) << "Remapped "
817 << aos::configuration::StrippedChannelToString(remapped_channel);
818
819 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
820 // we want it to degrade if the heuristics fail to just work.
821 //
822 // The easiest way to do this is going to be incredibly specific and verbose.
823 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
824 // /original/0/spray. Then, create a map from /original/spray to
825 // /original/0/spray for just the type we were asked for.
826 if (name != remapped_channel->name()->string_view()) {
827 MapT new_map;
828 new_map.match = std::make_unique<ChannelT>();
829 new_map.match->name = absl::StrCat(add_prefix, name);
830 new_map.match->type = type;
831 if (node != nullptr) {
832 new_map.match->source_node = node->name()->str();
833 }
834 new_map.rename = std::make_unique<ChannelT>();
835 new_map.rename->name =
836 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
837 maps_.emplace_back(std::move(new_map));
838 }
839
840 const size_t channel_index =
841 configuration::ChannelIndex(logged_configuration(), remapped_channel);
842 CHECK_EQ(0u, remapped_channels_.count(channel_index))
843 << "Already remapped channel "
844 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800845
846 RemappedChannel remapped_channel_struct;
847 remapped_channel_struct.remapped_name =
848 std::string(add_prefix) +
849 std::string(remapped_channel->name()->string_view());
850 remapped_channel_struct.new_type = new_type;
851 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -0700852 MakeRemappedConfig();
853}
854
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800855void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -0800856 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800857 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700858 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -0800859 << ": Can't change the mapping after the events are scheduled.";
860 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800861 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800862
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800863 // If no remapping occurred and we are using the original config, then there
864 // is nothing interesting to do here.
865 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800866 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800867 return;
868 }
869 // Config to copy Channel definitions from. Use the specified
870 // replay_configuration_ if it has been provided.
871 const Configuration *const base_config = replay_configuration_ == nullptr
872 ? logged_configuration()
873 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -0800874
875 // Create a config with all the channels, but un-sorted/merged. Collect up
876 // the schemas while we do this. Call MergeConfiguration to sort everything,
877 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800878
879 // This is the builder that we use for the config containing all the new
880 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -0800881 flatbuffers::FlatBufferBuilder fbb;
882 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800883 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -0800884
885 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
886 << ": Merging logic needs to be updated when the number of channel "
887 "fields changes.";
888
889 // List of schemas.
890 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
891 // Make sure our new RemoteMessage schema is in there for old logs without it.
892 schema_map.insert(std::make_pair(
893 RemoteMessage::GetFullyQualifiedName(),
894 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
895 message_bridge::RemoteMessageSchema()))));
896
897 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800898 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -0800899 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800900 base_config, logged_configuration()->channels()->Get(pair.first), "",
901 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -0800902 channel_offsets.emplace_back(
903 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -0700904
905 if (c->has_destination_nodes()) {
906 for (const Connection *connection : *c->destination_nodes()) {
907 switch (connection->timestamp_logger()) {
908 case LoggerConfig::LOCAL_LOGGER:
909 case LoggerConfig::NOT_LOGGED:
910 // There is no timestamp channel associated with this, so ignore it.
911 break;
912
913 case LoggerConfig::REMOTE_LOGGER:
914 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
915 // We want to make a split timestamp channel regardless of what type
916 // of log this used to be. No sense propagating the single
917 // timestamp channel.
918
919 CHECK(connection->has_timestamp_logger_nodes());
920 for (const flatbuffers::String *timestamp_logger_node :
921 *connection->timestamp_logger_nodes()) {
922 const Node *node = configuration::GetNode(
923 logged_configuration(), timestamp_logger_node->string_view());
924 message_bridge::ChannelTimestampFinder finder(
925 logged_configuration(), "log_reader", node);
926
927 // We are assuming here that all the maps are setup correctly to
928 // handle arbitrary timestamps. Apply the maps for this node to
929 // see what name this ends up with.
930 std::string name = finder.SplitChannelName(
931 pair.second.remapped_name, c->type()->str(), connection);
932 std::string unmapped_name = name;
933 configuration::HandleMaps(logged_configuration()->maps(), &name,
934 "aos.message_bridge.RemoteMessage",
935 node);
936 CHECK_NE(name, unmapped_name)
937 << ": Remote timestamp channel was not remapped, this is "
938 "very fishy";
939 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
940 fbb.CreateString(name);
941 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
942 fbb.CreateString("aos.message_bridge.RemoteMessage");
943 flatbuffers::Offset<flatbuffers::String> source_node_offset =
944 fbb.CreateString(timestamp_logger_node->string_view());
945
946 // Now, build a channel. Don't log it, 2 senders, and match the
947 // source frequency.
948 Channel::Builder channel_builder(fbb);
949 channel_builder.add_name(channel_name_offset);
950 channel_builder.add_type(channel_type_offset);
951 channel_builder.add_source_node(source_node_offset);
952 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
953 channel_builder.add_num_senders(2);
954 if (c->has_frequency()) {
955 channel_builder.add_frequency(c->frequency());
956 }
957 channel_offsets.emplace_back(channel_builder.Finish());
958 }
959 break;
960 }
961 }
962 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800963 }
Austin Schuh01b4c352020-09-21 23:09:39 -0700964
Austin Schuh0de30f32020-12-06 12:44:28 -0800965 // Now reconstruct the original channels, translating types as needed
966 for (const Channel *c : *base_config->channels()) {
967 // Search for a mapping channel.
968 std::string_view new_type = "";
969 for (auto &pair : remapped_channels_) {
970 const Channel *const remapped_channel =
971 logged_configuration()->channels()->Get(pair.first);
972 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
973 remapped_channel->type()->string_view() == c->type()->string_view()) {
974 new_type = pair.second.new_type;
975 break;
976 }
977 }
978
979 // Copy everything over.
980 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
981
982 // Add the schema if it doesn't exist.
983 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
984 CHECK(c->has_schema());
985 schema_map.insert(std::make_pair(c->type()->string_view(),
986 RecursiveCopyFlatBuffer(c->schema())));
987 }
988 }
989
990 // The MergeConfiguration API takes a vector, not a map. Convert.
991 std::vector<FlatbufferVector<reflection::Schema>> schemas;
992 while (!schema_map.empty()) {
993 schemas.emplace_back(std::move(schema_map.begin()->second));
994 schema_map.erase(schema_map.begin());
995 }
996
997 // Create the Configuration containing the new channels that we want to add.
998 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
999 channels_offset =
1000 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1001
1002 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001003 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001004 if (base_config->maps()) {
1005 for (const Map *map : *base_config->maps()) {
1006 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1007 }
1008 }
1009
1010 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001011 for (const MapT &map : maps_) {
1012 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001013 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001014 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001015 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001016 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001017 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001018 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1019 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001020 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001021 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001022 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001023 match_builder.add_name(match_name_offset);
1024 match_builder.add_type(match_type_offset);
1025 if (!map.match->source_node.empty()) {
1026 match_builder.add_source_node(match_source_node_offset);
1027 }
1028 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1029
Austin Schuh0de30f32020-12-06 12:44:28 -08001030 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001031 rename_builder.add_name(rename_name_offset);
1032 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1033
Austin Schuh0de30f32020-12-06 12:44:28 -08001034 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001035 map_builder.add_match(match_offset);
1036 map_builder.add_rename(rename_offset);
1037 map_offsets.emplace_back(map_builder.Finish());
1038 }
1039
Austin Schuh0de30f32020-12-06 12:44:28 -08001040 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1041 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001042
Austin Schuh0de30f32020-12-06 12:44:28 -08001043 // And copy everything else over.
1044 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1045 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1046
1047 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1048 applications_offset =
1049 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1050
1051 // Now insert everything else in unmodified.
1052 ConfigurationBuilder configuration_builder(fbb);
1053 if (!channels_offset.IsNull()) {
1054 configuration_builder.add_channels(channels_offset);
1055 }
1056 if (!maps_offsets.IsNull()) {
1057 configuration_builder.add_maps(maps_offsets);
1058 }
1059 if (!nodes_offset.IsNull()) {
1060 configuration_builder.add_nodes(nodes_offset);
1061 }
1062 if (!applications_offset.IsNull()) {
1063 configuration_builder.add_applications(applications_offset);
1064 }
1065
1066 if (base_config->has_channel_storage_duration()) {
1067 configuration_builder.add_channel_storage_duration(
1068 base_config->channel_storage_duration());
1069 }
1070
1071 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1072 << ": Merging logic needs to be updated when the number of configuration "
1073 "fields changes.";
1074
1075 fbb.Finish(configuration_builder.Finish());
1076
1077 // Clean it up and return it! By using MergeConfiguration here, we'll
1078 // actually get a deduplicated config for free too.
1079 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1080 configuration::MergeConfiguration(
1081 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1082
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001083 remapped_configuration_buffer_ =
1084 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001085 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001086
1087 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001088
1089 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001090}
1091
Austin Schuh6f3babe2020-01-26 20:34:50 -08001092const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1093 const Channel *channel) {
1094 std::string_view channel_name = channel->name()->string_view();
1095 std::string_view channel_type = channel->type()->string_view();
1096 const int channel_index =
1097 configuration::ChannelIndex(logged_configuration(), channel);
1098 // If the channel is remapped, find the correct channel name to use.
1099 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001100 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001101 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001102 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001103 }
1104
Austin Schuhee711052020-08-24 16:06:09 -07001105 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001106 const Channel *remapped_channel = configuration::GetChannel(
1107 event_loop->configuration(), channel_name, channel_type,
1108 event_loop->name(), event_loop->node());
1109
1110 CHECK(remapped_channel != nullptr)
1111 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1112 << channel_type << "\"} because it is not in the provided configuration.";
1113
1114 return remapped_channel;
1115}
1116
Austin Schuh287d43d2020-12-04 20:19:33 -08001117LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1118 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1119
1120void LogReader::State::AddPeer(State *peer) {
1121 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1122 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1123 }
1124}
Austin Schuh858c9f32020-08-31 16:56:12 -07001125
1126EventLoop *LogReader::State::SetNodeEventLoopFactory(
1127 NodeEventLoopFactory *node_event_loop_factory) {
1128 node_event_loop_factory_ = node_event_loop_factory;
1129 event_loop_unique_ptr_ =
1130 node_event_loop_factory_->MakeEventLoop("log_reader");
1131 return event_loop_unique_ptr_.get();
1132}
1133
1134void LogReader::State::SetChannelCount(size_t count) {
1135 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001136 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001137 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001138 channel_source_state_.resize(count);
1139 factory_channel_index_.resize(count);
1140 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001141}
1142
1143void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001144 size_t logged_channel_index, size_t factory_channel_index,
1145 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001146 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001147 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001148 channels_[logged_channel_index] = std::move(sender);
1149 filters_[logged_channel_index] = filter;
1150 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1151
1152 if (source_state) {
1153 channel_source_state_[logged_channel_index] = source_state;
1154
1155 if (remote_timestamp_sender != nullptr) {
1156 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001157 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001158 }
1159 }
1160
1161 factory_channel_index_[logged_channel_index] = factory_channel_index;
1162}
1163
Austin Schuh287d43d2020-12-04 20:19:33 -08001164bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1165 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001166 uint32_t remote_queue_index = 0xffffffff;
1167
Austin Schuh287d43d2020-12-04 20:19:33 -08001168 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001169 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001170 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1171 ->queue_index_map_[timestamped_message.channel_index]
1172 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001173
Austin Schuh9942bae2021-01-07 22:06:44 -08001174 struct SentTimestamp {
1175 monotonic_clock::time_point monotonic_event_time;
1176 uint32_t queue_index;
1177 } search;
1178
Austin Schuh287d43d2020-12-04 20:19:33 -08001179 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001180 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001181
1182 // Find the sent time if available.
1183 auto element = std::lower_bound(
1184 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001185 [](ContiguousSentTimestamp a, SentTimestamp b) {
1186 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001187 return true;
1188 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001189 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001190 return false;
1191 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001192
1193 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001194 return true;
1195 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001196 if (a.starting_queue_index >= b.queue_index) {
1197 return false;
1198 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001199
Austin Schuh9942bae2021-01-07 22:06:44 -08001200 // If it isn't clearly below or above, it is below. Since we return
1201 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001202 return false;
1203 });
1204
1205 // TODO(austin): Be a bit more principled here, but we will want to do that
1206 // after the logger rewrite. We hit this when one node finishes, but the
1207 // other node isn't done yet. So there is no send time, but there is a
1208 // receive time.
1209 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001210 CHECK_GE(timestamped_message.monotonic_remote_time,
1211 element->starting_monotonic_event_time);
1212 CHECK_LE(timestamped_message.monotonic_remote_time,
1213 element->ending_monotonic_event_time);
1214 CHECK_GE(timestamped_message.remote_queue_index,
1215 element->starting_queue_index);
1216 CHECK_LE(timestamped_message.remote_queue_index,
1217 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001218
Austin Schuh9942bae2021-01-07 22:06:44 -08001219 remote_queue_index = timestamped_message.remote_queue_index +
1220 element->actual_queue_index -
1221 element->starting_queue_index;
1222 } else {
1223 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001224 }
1225 }
1226
1227 // Send! Use the replayed queue index here instead of the logged queue index
1228 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001229 const bool sent = sender->Send(
1230 timestamped_message.data.message().data()->Data(),
1231 timestamped_message.data.message().data()->size(),
1232 timestamped_message.monotonic_remote_time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001233 timestamped_message.realtime_remote_time, remote_queue_index,
1234 (channel_source_state_[timestamped_message.channel_index] != nullptr
1235 ? CHECK_NOTNULL(
1236 channel_source_state_[timestamped_message.channel_index])
1237 ->event_loop_->boot_uuid()
1238 : event_loop_->boot_uuid()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001239 if (!sent) return false;
1240
Austin Schuh287d43d2020-12-04 20:19:33 -08001241 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001242 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1243 // Nothing here, start a range with 0 length.
1244 ContiguousSentTimestamp timestamp;
1245 timestamp.starting_monotonic_event_time =
1246 timestamp.ending_monotonic_event_time =
1247 timestamped_message.monotonic_event_time;
1248 timestamp.starting_queue_index = timestamp.ending_queue_index =
1249 timestamped_message.queue_index;
1250 timestamp.actual_queue_index = sender->sent_queue_index();
1251 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1252 timestamp);
1253 } else {
1254 // We've got something. See if the next timestamp is still contiguous. If
1255 // so, grow it.
1256 ContiguousSentTimestamp *back =
1257 &queue_index_map_[timestamped_message.channel_index]->back();
1258 if ((back->starting_queue_index - back->actual_queue_index) ==
1259 (timestamped_message.queue_index - sender->sent_queue_index())) {
1260 back->ending_queue_index = timestamped_message.queue_index;
1261 back->ending_monotonic_event_time =
1262 timestamped_message.monotonic_event_time;
1263 } else {
1264 // Otherwise, make a new one.
1265 ContiguousSentTimestamp timestamp;
1266 timestamp.starting_monotonic_event_time =
1267 timestamp.ending_monotonic_event_time =
1268 timestamped_message.monotonic_event_time;
1269 timestamp.starting_queue_index = timestamp.ending_queue_index =
1270 timestamped_message.queue_index;
1271 timestamp.actual_queue_index = sender->sent_queue_index();
1272 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1273 timestamp);
1274 }
1275 }
1276
1277 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1278 // queue index diverge a couple of elements, which would be a very small
1279 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001280 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1281 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001282 flatbuffers::FlatBufferBuilder fbb;
1283 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001284 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1285 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001286
Austin Schuh969cd602021-01-03 00:09:45 -08001287 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001288
1289 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001290 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001291
1292 // Swap the remote and sent metrics. They are from the sender's
1293 // perspective, not the receiver's perspective.
1294 message_header_builder.add_monotonic_sent_time(
1295 sender->monotonic_sent_time().time_since_epoch().count());
1296 message_header_builder.add_realtime_sent_time(
1297 sender->realtime_sent_time().time_since_epoch().count());
1298 message_header_builder.add_queue_index(sender->sent_queue_index());
1299
1300 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001301 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001302 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001303 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001304
1305 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001306 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001307
Austin Schuh969cd602021-01-03 00:09:45 -08001308 fbb.Finish(message_header_builder.Finish());
1309
1310 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1311 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
1312 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001313 }
1314
1315 return true;
1316}
1317
Austin Schuh969cd602021-01-03 00:09:45 -08001318LogReader::RemoteMessageSender::RemoteMessageSender(
1319 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1320 : event_loop_(event_loop),
1321 sender_(std::move(sender)),
1322 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1323
1324void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1325 if (remote_timestamps_.empty()) {
1326 CHECK_NOTNULL(timer_);
1327 timer_->Disable();
1328 scheduled_time_ = monotonic_clock::min_time;
1329 return;
1330 }
1331
1332 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1333 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001334 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001335 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001336 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1337 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001338 }
1339}
1340
1341void LogReader::RemoteMessageSender::Send(
1342 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
1343 monotonic_clock::time_point monotonic_timestamp_time) {
1344 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
1345 // resend the timestamp at the correct time, or we don't and can send it
1346 // immediately.
1347 if (monotonic_timestamp_time == monotonic_clock::min_time) {
1348 CHECK(remote_timestamps_.empty())
1349 << ": Unsupported mix of timestamps and no timestamps.";
1350 sender_.Send(std::move(remote_message));
1351 } else {
Austin Schuhb22ae422021-01-31 17:57:06 -08001352 remote_timestamps_.emplace(
1353 std::upper_bound(
1354 remote_timestamps_.begin(), remote_timestamps_.end(),
1355 monotonic_timestamp_time,
1356 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1357 const Timestamp &timestamp) {
1358 return monotonic_timestamp_time <
1359 timestamp.monotonic_timestamp_time;
1360 }),
1361 std::move(remote_message), monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001362 ScheduleTimestamp();
1363 }
1364}
1365
1366void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001367 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1368 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001369 CHECK(!remote_timestamps_.empty());
1370
1371 // Send out all timestamps at the currently scheduled time.
1372 while (remote_timestamps_.front().monotonic_timestamp_time ==
1373 scheduled_time_) {
1374 sender_.Send(std::move(remote_timestamps_.front().remote_message));
1375 remote_timestamps_.pop_front();
1376 if (remote_timestamps_.empty()) {
1377 break;
1378 }
1379 }
1380 scheduled_time_ = monotonic_clock::min_time;
1381
1382 ScheduleTimestamp();
1383}
1384
1385LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001386 const Channel *channel, const Connection *connection) {
1387 message_bridge::ChannelTimestampFinder finder(event_loop_);
1388 // Look at any pre-created channel/connection pairs.
1389 {
1390 auto it =
1391 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1392 if (it != channel_timestamp_loggers_.end()) {
1393 return it->second.get();
1394 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001395 }
1396
Austin Schuh61e973f2021-02-21 21:43:56 -08001397 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1398 // to.
1399 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1400
1401 {
1402 // See if that has been created before. If so, cache it in
1403 // channel_timestamp_loggers_ and return.
1404 auto it = timestamp_loggers_.find(timestamp_channel);
1405 if (it != timestamp_loggers_.end()) {
1406 CHECK(channel_timestamp_loggers_
1407 .try_emplace(std::make_pair(channel, connection), it->second)
1408 .second);
1409 return it->second.get();
1410 }
1411 }
1412
1413 // Otherwise, make a sender, save it, and cache it.
1414 auto result = channel_timestamp_loggers_.try_emplace(
1415 std::make_pair(channel, connection),
1416 std::make_shared<RemoteMessageSender>(
1417 event_loop()->MakeSender<RemoteMessage>(
1418 timestamp_channel->name()->string_view()),
1419 event_loop()));
1420
1421 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1422 .second);
1423 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001424}
1425
Austin Schuhdda74ec2021-01-03 19:30:37 -08001426TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001427 CHECK(timestamp_mapper_ != nullptr);
1428 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1429 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001430
Austin Schuhe639ea12021-01-25 13:00:22 -08001431 TimestampedMessage result = std::move(*result_ptr);
1432
Austin Schuh2f8fd752020-09-01 22:38:28 -07001433 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001434 << result.monotonic_event_time;
1435 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001436 SeedSortedMessages();
1437
Austin Schuhe639ea12021-01-25 13:00:22 -08001438 if (result.monotonic_remote_time != monotonic_clock::min_time) {
1439 message_bridge::NoncausalOffsetEstimator *filter =
1440 filters_[result.channel_index];
1441 CHECK(filter != nullptr);
1442
1443 // TODO(austin): We probably want to push this down into the timestamp
1444 // mapper directly.
Austin Schuh3d94be02021-02-12 23:15:20 -08001445 filter->Pop(event_loop_->node(), event_loop_->monotonic_now());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001446 }
Austin Schuh5ee56872021-01-30 16:53:34 -08001447 VLOG(1) << "Popped " << result
1448 << configuration::CleanedChannelToString(
1449 event_loop_->configuration()->channels()->Get(
1450 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001451 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001452}
1453
1454monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
Austin Schuhe639ea12021-01-25 13:00:22 -08001455 if (timestamp_mapper_ == nullptr) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001456 return monotonic_clock::max_time;
1457 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001458 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1459 if (result_ptr == nullptr) {
1460 return monotonic_clock::max_time;
1461 }
1462 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
1463 << result_ptr->monotonic_event_time;
1464 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001465}
1466
1467void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001468 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001469
Austin Schuhe639ea12021-01-25 13:00:22 -08001470 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1471 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001472}
1473
1474void LogReader::State::Deregister() {
1475 for (size_t i = 0; i < channels_.size(); ++i) {
1476 channels_[i].reset();
1477 }
Austin Schuh61e973f2021-02-21 21:43:56 -08001478 channel_timestamp_loggers_.clear();
1479 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001480 event_loop_unique_ptr_.reset();
1481 event_loop_ = nullptr;
1482 timer_handler_ = nullptr;
1483 node_event_loop_factory_ = nullptr;
1484}
1485
Austin Schuhe309d2a2019-11-29 13:25:21 -08001486} // namespace logger
1487} // namespace aos