blob: 35ef49838db437707114d04a2d1857da43083b25 [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#include "aos/events/logging/log_reader.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08007
Tyler Chatowbf0609c2021-07-31 16:13:27 -07008#include <climits>
Austin Schuhe309d2a2019-11-29 13:25:21 -08009#include <vector>
10
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuh2dc8c7d2021-07-01 17:41:28 -070014#include "aos/events/logging/boot_timestamp.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070015#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080016#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080018#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080019#include "aos/network/remote_message_generated.h"
20#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080021#include "aos/network/team_number.h"
Austin Schuh61e973f2021-02-21 21:43:56 -080022#include "aos/network/timestamp_channel.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080023#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070024#include "aos/util/file.h"
Austin Schuh4385b142021-03-14 21:31:13 -070025#include "aos/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080026#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080027#include "openssl/sha.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080028
Austin Schuh15649d62019-12-28 16:36:38 -080029DEFINE_bool(skip_missing_forwarding_entries, false,
30 "If true, drop any forwarding entries with missing data. If "
31 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080032
Austin Schuh0ca1fd32020-12-18 22:53:05 -080033DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080034
Austin Schuh2f8fd752020-09-01 22:38:28 -070035DEFINE_bool(skip_order_validation, false,
36 "If true, ignore any out of orderness in replay");
37
Austin Schuhf0688662020-12-19 15:37:45 -080038DEFINE_double(
39 time_estimation_buffer_seconds, 2.0,
40 "The time to buffer ahead in the log file to accurately reconstruct time.");
41
Austin Schuhe309d2a2019-11-29 13:25:21 -080042namespace aos {
Austin Schuh006a9f52021-04-07 16:24:18 -070043namespace configuration {
44// We don't really want to expose this publicly, but log reader doesn't really
45// want to re-implement it.
46void HandleMaps(const flatbuffers::Vector<flatbuffers::Offset<aos::Map>> *maps,
47 std::string *name, std::string_view type, const Node *node);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070048} // namespace configuration
Austin Schuhe309d2a2019-11-29 13:25:21 -080049namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070050namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080051
Austin Schuh1c227352021-09-17 12:53:54 -070052bool CompareChannels(const Channel *c,
53 ::std::pair<std::string_view, std::string_view> p) {
54 int name_compare = c->name()->string_view().compare(p.first);
55 if (name_compare == 0) {
56 return c->type()->string_view() < p.second;
57 } else if (name_compare < 0) {
58 return true;
59 } else {
60 return false;
61 }
62}
63
64bool EqualsChannels(const Channel *c,
65 ::std::pair<std::string_view, std::string_view> p) {
66 return c->name()->string_view() == p.first &&
67 c->type()->string_view() == p.second;
68}
69
Austin Schuh0de30f32020-12-06 12:44:28 -080070// Copies the channel, removing the schema as we go. If new_name is provided,
71// it is used instead of the name inside the channel. If new_type is provided,
72// it is used instead of the type in the channel.
73flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
74 std::string_view new_name,
75 std::string_view new_type,
76 flatbuffers::FlatBufferBuilder *fbb) {
77 flatbuffers::Offset<flatbuffers::String> name_offset =
78 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
79 : new_name);
80 flatbuffers::Offset<flatbuffers::String> type_offset =
81 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
82 flatbuffers::Offset<flatbuffers::String> source_node_offset =
83 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
84 : 0;
85
86 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
87 destination_nodes_offset =
88 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
89
90 flatbuffers::Offset<
91 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
92 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
93
94 Channel::Builder channel_builder(*fbb);
95 channel_builder.add_name(name_offset);
96 channel_builder.add_type(type_offset);
97 if (c->has_frequency()) {
98 channel_builder.add_frequency(c->frequency());
99 }
100 if (c->has_max_size()) {
101 channel_builder.add_max_size(c->max_size());
102 }
103 if (c->has_num_senders()) {
104 channel_builder.add_num_senders(c->num_senders());
105 }
106 if (c->has_num_watchers()) {
107 channel_builder.add_num_watchers(c->num_watchers());
108 }
109 if (!source_node_offset.IsNull()) {
110 channel_builder.add_source_node(source_node_offset);
111 }
112 if (!destination_nodes_offset.IsNull()) {
113 channel_builder.add_destination_nodes(destination_nodes_offset);
114 }
115 if (c->has_logger()) {
116 channel_builder.add_logger(c->logger());
117 }
118 if (!logger_nodes_offset.IsNull()) {
119 channel_builder.add_logger_nodes(logger_nodes_offset);
120 }
121 if (c->has_read_method()) {
122 channel_builder.add_read_method(c->read_method());
123 }
124 if (c->has_num_readers()) {
125 channel_builder.add_num_readers(c->num_readers());
126 }
127 return channel_builder.Finish();
128}
129
Austin Schuhe309d2a2019-11-29 13:25:21 -0800130namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800131using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700132} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800133
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800134LogReader::LogReader(std::string_view filename,
135 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800136 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800137
Austin Schuh287d43d2020-12-04 20:19:33 -0800138LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800139 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800140 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800141 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800142 CHECK_GT(log_files_.size(), 0u);
143 {
144 // Validate that we have the same config everwhere. This will be true if
145 // all the parts were sorted together and the configs match.
146 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800147 for (const LogFile &log_file : log_files_) {
148 if (log_file.config.get() == nullptr) {
149 LOG(FATAL) << "Couldn't find a config in " << log_file;
150 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800151 if (config == nullptr) {
152 config = log_file.config.get();
153 } else {
154 CHECK_EQ(config, log_file.config.get());
155 }
156 }
157 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800158
Austin Schuh6331ef92020-01-07 18:28:09 -0800159 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800160
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700161 // Remap all existing remote timestamp channels. They will be recreated, and
162 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700163 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh61e973f2021-02-21 21:43:56 -0800164 message_bridge::ChannelTimestampFinder finder(logged_configuration(),
165 "log_reader", node);
166
167 absl::btree_set<std::string_view> remote_nodes;
168
169 for (const Channel *channel : *logged_configuration()->channels()) {
170 if (!configuration::ChannelIsSendableOnNode(channel, node)) {
171 continue;
172 }
173 if (!channel->has_destination_nodes()) {
174 continue;
175 }
176 for (const Connection *connection : *channel->destination_nodes()) {
177 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
178 node)) {
179 // Start by seeing if the split timestamp channels are being used for
180 // this message. If so, remap them.
181 const Channel *timestamp_channel = configuration::GetChannel(
182 logged_configuration(),
183 finder.SplitChannelName(channel, connection),
184 RemoteMessage::GetFullyQualifiedName(), "", node, true);
185
186 if (timestamp_channel != nullptr) {
187 if (timestamp_channel->logger() != LoggerConfig::NOT_LOGGED) {
188 RemapLoggedChannel<RemoteMessage>(
189 timestamp_channel->name()->string_view(), node);
190 }
191 continue;
192 }
193
194 // Otherwise collect this one up as a node to look for a combined
195 // channel from. It is more efficient to compare nodes than channels.
196 remote_nodes.insert(connection->name()->string_view());
197 }
198 }
199 }
200
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700201 std::vector<const Node *> timestamp_logger_nodes =
202 configuration::TimestampNodes(logged_configuration(), node);
Austin Schuh61e973f2021-02-21 21:43:56 -0800203 for (const std::string_view remote_node : remote_nodes) {
204 const std::string channel = finder.CombinedChannelName(remote_node);
205
Austin Schuh0de30f32020-12-06 12:44:28 -0800206 // See if the log file is an old log with MessageHeader channels in it, or
207 // a newer log with RemoteMessage. If we find an older log, rename the
208 // type too along with the name.
209 if (HasChannel<MessageHeader>(channel, node)) {
210 CHECK(!HasChannel<RemoteMessage>(channel, node))
211 << ": Can't have both a MessageHeader and RemoteMessage remote "
212 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800213 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
214 // careful about updating the config, but there are fewer and fewer logs
215 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800216 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
217 "aos.message_bridge.RemoteMessage");
218 } else {
219 CHECK(HasChannel<RemoteMessage>(channel, node))
220 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
221 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
222 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800223 // Only bother to remap if there's something on the channel. We can
224 // tell if the channel was marked NOT_LOGGED or not. This makes the
225 // config not change un-necesarily when we replay a log with NOT_LOGGED
226 // messages.
227 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
228 RemapLoggedChannel<RemoteMessage>(channel, node);
229 }
Austin Schuh0de30f32020-12-06 12:44:28 -0800230 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700231 }
232 }
233
Austin Schuh6aa77be2020-02-22 21:06:40 -0800234 if (replay_configuration) {
235 CHECK_EQ(configuration::MultiNode(configuration()),
236 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700237 << ": Log file and replay config need to both be multi or single "
238 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800239 }
240
Austin Schuh6f3babe2020-01-26 20:34:50 -0800241 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800242 states_.emplace_back(std::make_unique<State>(
Austin Schuh58646e22021-08-23 23:51:46 -0700243 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, "")),
244 nullptr));
Austin Schuh8bd96322020-02-13 21:18:22 -0800245 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800246 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700247 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800248 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700249 << ": Log file and replay config need to have matching nodes "
250 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700251 for (const Node *node : *logged_configuration()->nodes()) {
252 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700253 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
254 << " in logged config that is not present in the replay "
255 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700256 }
257 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800258 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800259 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800260 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800261}
262
Austin Schuh6aa77be2020-02-22 21:06:40 -0800263LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700264 if (event_loop_factory_unique_ptr_) {
265 Deregister();
266 } else if (event_loop_factory_ != nullptr) {
267 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
268 "is destroyed";
269 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700270 // Zero out some buffers. It's easy to do use-after-frees on these, so make
271 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700272 if (remapped_configuration_buffer_) {
273 remapped_configuration_buffer_->Wipe();
274 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800275}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800276
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800277const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800278 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800279}
280
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800281const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800282 return remapped_configuration_;
283}
284
Austin Schuh07676622021-01-21 18:59:17 -0800285std::vector<const Node *> LogReader::LoggedNodes() const {
286 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800287}
Austin Schuh15649d62019-12-28 16:36:38 -0800288
Austin Schuh11d43732020-09-21 17:28:30 -0700289monotonic_clock::time_point LogReader::monotonic_start_time(
290 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800291 State *state =
292 states_[configuration::GetNodeIndex(configuration(), node)].get();
293 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
294
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700295 // TODO(austin): Un-hard-code the 0 boot count.
296 return state->monotonic_start_time(0);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800297}
298
Austin Schuh11d43732020-09-21 17:28:30 -0700299realtime_clock::time_point LogReader::realtime_start_time(
300 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800301 State *state =
302 states_[configuration::GetNodeIndex(configuration(), node)].get();
303 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
304
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700305 // TODO(austin): Un-hard-code the 0 boot count.
306 return state->realtime_start_time(0);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800307}
308
Austin Schuh58646e22021-08-23 23:51:46 -0700309void LogReader::OnStart(std::function<void()> fn) {
310 CHECK(!configuration::MultiNode(configuration()));
311 OnStart(nullptr, std::move(fn));
312}
313
314void LogReader::OnStart(const Node *node, std::function<void()> fn) {
315 const int node_index = configuration::GetNodeIndex(configuration(), node);
316 CHECK_GE(node_index, 0);
317 CHECK_LT(node_index, static_cast<int>(states_.size()));
318 State *state = states_[node_index].get();
319 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
320
321 state->OnStart(std::move(fn));
322}
323
324void LogReader::State::OnStart(std::function<void()> fn) {
325 on_starts_.emplace_back(std::move(fn));
326}
327
328void LogReader::State::RunOnStart() {
329 SetRealtimeOffset(monotonic_start_time(boot_count()),
330 realtime_start_time(boot_count()));
331
332 VLOG(1) << "Starting " << MaybeNodeName(node()) << "at time "
333 << monotonic_start_time(boot_count());
334 for (size_t i = 0; i < on_starts_.size(); ++i) {
335 on_starts_[i]();
336 }
337 stopped_ = false;
338 started_ = true;
339}
340
341void LogReader::OnEnd(std::function<void()> fn) {
342 CHECK(!configuration::MultiNode(configuration()));
343 OnEnd(nullptr, std::move(fn));
344}
345
346void LogReader::OnEnd(const Node *node, std::function<void()> fn) {
347 const int node_index = configuration::GetNodeIndex(configuration(), node);
348 CHECK_GE(node_index, 0);
349 CHECK_LT(node_index, static_cast<int>(states_.size()));
350 State *state = states_[node_index].get();
351 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
352
353 state->OnEnd(std::move(fn));
354}
355
356void LogReader::State::OnEnd(std::function<void()> fn) {
357 on_ends_.emplace_back(std::move(fn));
358}
359
360void LogReader::State::RunOnEnd() {
361 VLOG(1) << "Ending " << MaybeNodeName(node()) << "at time "
362 << monotonic_start_time(boot_count());
363 for (size_t i = 0; i < on_ends_.size(); ++i) {
364 on_ends_[i]();
365 }
366
367 stopped_ = true;
368 started_ = false;
369}
370
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800371void LogReader::Register() {
372 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800373 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800374 Register(event_loop_factory_unique_ptr_.get());
375}
376
Austin Schuh58646e22021-08-23 23:51:46 -0700377void LogReader::RegisterWithoutStarting(
378 SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800379 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700380 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800381 filters_ =
382 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -0800383 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuh58646e22021-08-23 23:51:46 -0700384 log_files_[0].boots, FLAGS_skip_order_validation,
Austin Schuhfe3fb342021-01-16 18:50:37 -0800385 chrono::duration_cast<chrono::nanoseconds>(
386 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -0800387
Austin Schuhe639ea12021-01-25 13:00:22 -0800388 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -0700389 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800390 const size_t node_index =
391 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800392 std::vector<LogParts> filtered_parts = FilterPartsForNode(
393 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -0800394
Austin Schuh287d43d2020-12-04 20:19:33 -0800395 states_[node_index] = std::make_unique<State>(
396 filtered_parts.size() == 0u
397 ? nullptr
Austin Schuh58646e22021-08-23 23:51:46 -0700398 : std::make_unique<TimestampMapper>(std::move(filtered_parts)),
399 node);
Austin Schuh8bd96322020-02-13 21:18:22 -0800400 State *state = states_[node_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -0700401 state->SetNodeEventLoopFactory(
402 event_loop_factory_->GetNodeEventLoopFactory(node));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700403
404 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -0800405 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -0800406 }
Austin Schuhe639ea12021-01-25 13:00:22 -0800407 filters_->SetTimestampMappers(std::move(timestamp_mappers));
408
409 // Note: this needs to be set before any times are pulled, or we won't observe
410 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -0800411 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700412
Austin Schuh287d43d2020-12-04 20:19:33 -0800413 for (const Node *node : configuration::GetNodes(configuration())) {
414 const size_t node_index =
415 configuration::GetNodeIndex(configuration(), node);
416 State *state = states_[node_index].get();
417 for (const Node *other_node : configuration::GetNodes(configuration())) {
418 const size_t other_node_index =
419 configuration::GetNodeIndex(configuration(), other_node);
420 State *other_state = states_[other_node_index].get();
421 if (other_state != state) {
422 state->AddPeer(other_state);
423 }
424 }
425 }
426
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700427 // Register after making all the State objects so we can build references
428 // between them.
429 for (const Node *node : configuration::GetNodes(configuration())) {
430 const size_t node_index =
431 configuration::GetNodeIndex(configuration(), node);
432 State *state = states_[node_index].get();
433
Austin Schuh58646e22021-08-23 23:51:46 -0700434 // If we didn't find any log files with data in them, we won't ever get a
435 // callback or be live. So skip the rest of the setup.
436 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
437 continue;
438 }
439 ++live_nodes_;
440
441 NodeEventLoopFactory *node_factory =
442 event_loop_factory_->GetNodeEventLoopFactory(node);
443 node_factory->OnStartup([this, state, node]() {
444 RegisterDuringStartup(state->MakeEventLoop(), node);
445 });
446 node_factory->OnShutdown([this, state, node]() {
447 RegisterDuringStartup(nullptr, node);
448 state->DestroyEventLoop();
449 });
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700450 }
451
James Kuszmaul46d82582020-05-09 19:50:09 -0700452 if (live_nodes_ == 0) {
453 LOG(FATAL)
454 << "Don't have logs from any of the nodes in the replay config--are "
455 "you sure that the replay config matches the original config?";
456 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800457
Austin Schuh87dd3832021-01-01 23:07:31 -0800458 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800459
Austin Schuh858c9f32020-08-31 16:56:12 -0700460 for (std::unique_ptr<State> &state : states_) {
461 state->SeedSortedMessages();
462 }
463
Austin Schuh6f3babe2020-01-26 20:34:50 -0800464 // Forwarding is tracked per channel. If it is enabled, we want to turn it
465 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700466 // nodes, and also replayed on the other nodes. This may not satisfy all
467 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800468 if (configuration::MultiNode(event_loop_factory_->configuration())) {
469 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
470 const Channel *channel = logged_configuration()->channels()->Get(i);
471 const Node *node = configuration::GetNode(
472 configuration(), channel->source_node()->string_view());
473
Austin Schuh8bd96322020-02-13 21:18:22 -0800474 State *state =
475 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800476
477 const Channel *remapped_channel =
Austin Schuh58646e22021-08-23 23:51:46 -0700478 RemapChannel(state->event_loop(), node, channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800479
480 event_loop_factory_->DisableForwarding(remapped_channel);
481 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700482
483 // If we are replaying a log, we don't want a bunch of redundant messages
484 // from both the real message bridge and simulated message bridge.
485 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800486 }
Austin Schuh891214d2021-11-11 20:35:02 -0800487
488 // Write pseudo start times out to file now that we are all setup.
489 filters_->Start(event_loop_factory_);
Austin Schuh58646e22021-08-23 23:51:46 -0700490}
491
492void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
493 RegisterWithoutStarting(event_loop_factory);
494 // We want to start the log file at the last start time of the log files
495 // from all the nodes. Compute how long each node's simulation needs to run
496 // to move time to this point.
497 distributed_clock::time_point start_time = distributed_clock::min_time;
498
499 // TODO(austin): We want an "OnStart" callback for each node rather than
500 // running until the last node.
501
502 for (std::unique_ptr<State> &state : states_) {
503 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
504 << " for node " << MaybeNodeName(state->node()) << "now "
505 << state->monotonic_now();
506 if (state->monotonic_start_time(0) == monotonic_clock::min_time) {
507 continue;
508 }
509 // And start computing the start time on the distributed clock now that
510 // that works.
511 start_time = std::max(
512 start_time, state->ToDistributedClock(state->monotonic_start_time(0)));
513 }
514
515 // TODO(austin): If a node doesn't have a start time, we might not queue
516 // enough. If this happens, we'll explode with a frozen error eventually.
517
518 CHECK_GE(start_time, distributed_clock::epoch())
519 << ": Hmm, we have a node starting before the start of time. Offset "
520 "everything.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800521
Austin Schuhcde938c2020-02-02 17:30:07 -0800522 // While we are starting the system up, we might be relying on matching data
523 // to timestamps on log files where the timestamp log file starts before the
524 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800525 {
526 const bool prior_ignore_missing_data = ignore_missing_data_;
527 ignore_missing_data_ = true;
528 VLOG(1) << "Running until " << start_time << " in Register";
529 event_loop_factory_->RunFor(start_time.time_since_epoch());
530 VLOG(1) << "At start time";
531 // Now that we are running for real, missing data means that the log file is
532 // corrupted or went wrong.
533 ignore_missing_data_ = prior_ignore_missing_data;
534 }
Austin Schuh92547522019-12-28 14:33:43 -0800535
Austin Schuh8bd96322020-02-13 21:18:22 -0800536 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700537 // Make the RT clock be correct before handing it to the user.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700538 if (state->realtime_start_time(0) != realtime_clock::min_time) {
539 state->SetRealtimeOffset(state->monotonic_start_time(0),
540 state->realtime_start_time(0));
Austin Schuh2f8fd752020-09-01 22:38:28 -0700541 }
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700542 VLOG(1) << "Start time is " << state->monotonic_start_time(0)
543 << " for node " << MaybeNodeName(state->event_loop()->node())
544 << "now " << state->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700545 }
546
547 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800548 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -0800549 }
550}
551
Austin Schuh2f8fd752020-09-01 22:38:28 -0700552message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -0800553 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800554 if (filters_) {
555 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -0800556 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -0800557 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -0800558}
559
Austin Schuhe309d2a2019-11-29 13:25:21 -0800560void LogReader::Register(EventLoop *event_loop) {
Austin Schuh58646e22021-08-23 23:51:46 -0700561 Register(event_loop, event_loop->node());
562}
563
564void LogReader::Register(EventLoop *event_loop, const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800565 State *state =
Austin Schuh58646e22021-08-23 23:51:46 -0700566 states_[configuration::GetNodeIndex(configuration(), node)].get();
567
568 // If we didn't find any log files with data in them, we won't ever get a
569 // callback or be live. So skip the rest of the setup.
570 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
571 return;
572 }
573 ++live_nodes_;
574
575 if (event_loop_factory_ != nullptr) {
576 event_loop_factory_->GetNodeEventLoopFactory(node)->OnStartup(
577 [this, event_loop, node]() {
578 RegisterDuringStartup(event_loop, node);
579 });
580 } else {
581 RegisterDuringStartup(event_loop, node);
582 }
583}
584
585void LogReader::RegisterDuringStartup(EventLoop *event_loop, const Node *node) {
586 if (event_loop) {
587 CHECK(event_loop->configuration() == configuration());
588 }
589
590 State *state =
591 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800592
Austin Schuh858c9f32020-08-31 16:56:12 -0700593 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800594
Tyler Chatow67ddb032020-01-12 14:30:04 -0800595 // We don't run timing reports when trying to print out logged data, because
596 // otherwise we would end up printing out the timing reports themselves...
597 // This is only really relevant when we are replaying into a simulation.
Austin Schuh58646e22021-08-23 23:51:46 -0700598 if (event_loop) {
599 event_loop->SkipTimingReport();
600 event_loop->SkipAosLog();
601 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800602
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700603 for (size_t logged_channel_index = 0;
604 logged_channel_index < logged_configuration()->channels()->size();
605 ++logged_channel_index) {
606 const Channel *channel = RemapChannel(
Austin Schuh58646e22021-08-23 23:51:46 -0700607 event_loop, node,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700608 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -0800609
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700610 const bool logged = channel->logger() != LoggerConfig::NOT_LOGGED;
Austin Schuh532656d2021-01-11 10:17:18 -0800611
Austin Schuh2f8fd752020-09-01 22:38:28 -0700612 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700613
614 State *source_state = nullptr;
Austin Schuh58646e22021-08-23 23:51:46 -0700615 if (!configuration::ChannelIsSendableOnNode(channel, node) &&
616 configuration::ChannelIsReadableOnNode(channel, node)) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700617 const Node *source_node = configuration::GetNode(
Austin Schuh58646e22021-08-23 23:51:46 -0700618 configuration(), channel->source_node()->string_view());
Austin Schuh8bd96322020-02-13 21:18:22 -0800619
Austin Schuh58646e22021-08-23 23:51:46 -0700620 // We've got a message which is being forwarded to this node.
621 filter = GetFilter(node, source_node);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700622
623 source_state =
624 states_[configuration::GetNodeIndex(configuration(), source_node)]
625 .get();
Austin Schuh8bd96322020-02-13 21:18:22 -0800626 }
Austin Schuh858c9f32020-08-31 16:56:12 -0700627
Austin Schuh58646e22021-08-23 23:51:46 -0700628 // We are the source, and it is forwarded.
629 const bool is_forwarded =
630 configuration::ChannelIsSendableOnNode(channel, node) &&
631 configuration::ConnectionCount(channel);
632
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700633 state->SetChannel(
634 logged_channel_index,
635 configuration::ChannelIndex(configuration(), channel),
636 event_loop && logged ? event_loop->MakeRawSender(channel) : nullptr,
637 filter, is_forwarded, source_state);
Austin Schuh58646e22021-08-23 23:51:46 -0700638
Austin Schuhc0b6c4f2021-10-11 18:28:38 -0700639 if (is_forwarded && logged) {
Austin Schuh58646e22021-08-23 23:51:46 -0700640 const Node *source_node = configuration::GetNode(
641 configuration(), channel->source_node()->string_view());
642
643 for (const Connection *connection : *channel->destination_nodes()) {
644 const bool delivery_time_is_logged =
645 configuration::ConnectionDeliveryTimeIsLoggedOnNode(connection,
646 source_node);
647
648 if (delivery_time_is_logged) {
649 State *destination_state =
650 states_[configuration::GetNodeIndex(
651 configuration(), connection->name()->string_view())]
652 .get();
653 destination_state->SetRemoteTimestampSender(
654 logged_channel_index,
655 event_loop ? state->RemoteTimestampSender(channel, connection)
656 : nullptr);
657 }
658 }
659 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800660 }
661
Austin Schuh58646e22021-08-23 23:51:46 -0700662 if (!event_loop) {
663 state->ClearRemoteTimestampSenders();
664 state->set_timer_handler(nullptr);
665 state->set_startup_timer(nullptr);
Austin Schuh6aa77be2020-02-22 21:06:40 -0800666 return;
667 }
668
Austin Schuh858c9f32020-08-31 16:56:12 -0700669 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700670 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
671 << "at " << state->event_loop()->context().monotonic_event_time
672 << " now " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700673 if (state->OldestMessageTime() == BootTimestamp::max_time()) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800674 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700675 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -0800676 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800677 event_loop_factory_->Exit();
678 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800679 return;
680 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700681
Austin Schuhdda74ec2021-01-03 19:30:37 -0800682 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh58646e22021-08-23 23:51:46 -0700683
684 CHECK_EQ(timestamped_message.monotonic_event_time.boot,
685 state->boot_count());
Austin Schuh05b70472020-01-01 17:11:17 -0800686
Austin Schuhe309d2a2019-11-29 13:25:21 -0800687 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -0700688 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700689 if (!FLAGS_skip_order_validation) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700690 CHECK(monotonic_now == timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700691 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
692 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800693 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700694 << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700695 } else if (BootTimestamp{.boot = state->boot_count(),
696 .time = monotonic_now} !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700697 timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700698 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -0800699 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700700 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -0800701 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700702 << "): " << FlatbufferToJson(state->event_loop()->node())
703 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -0800704 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -0700705 << state->DebugString();
706 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800707
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700708 if (timestamped_message.monotonic_event_time.time >
709 state->monotonic_start_time(
710 timestamped_message.monotonic_event_time.boot) ||
Austin Schuh15649d62019-12-28 16:36:38 -0800711 event_loop_factory_ != nullptr) {
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700712 if (timestamped_message.data != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800713 if (timestamped_message.monotonic_remote_time !=
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700714 BootTimestamp::min_time()) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800715 // Confirm that the message was sent on the sending node before the
716 // destination node (this node). As a proxy, do this by making sure
717 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -0800718 //
719 // TODO(austin): <= means that the cause message (which we know) could
720 // happen after the effect even though we know they are at the same
721 // time. I doubt anyone will notice for a bit, but we should really
722 // fix that.
Austin Schuh58646e22021-08-23 23:51:46 -0700723 BootTimestamp monotonic_remote_now =
724 state->monotonic_remote_now(timestamped_message.channel_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700725 if (!FLAGS_skip_order_validation) {
Austin Schuh58646e22021-08-23 23:51:46 -0700726 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
Austin Schuh3e20c692021-11-16 20:43:16 -0800727 monotonic_remote_now.boot)
728 << state->event_loop()->node()->name()->string_view() << " to "
729 << state->remote_node(timestamped_message.channel_index)
730 ->name()
731 ->string_view()
732 << " while trying to send a message on "
733 << configuration::CleanedChannelToString(
734 logged_configuration()->channels()->Get(
735 timestamped_message.channel_index))
736 << " " << timestamped_message << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700737 CHECK_LE(timestamped_message.monotonic_remote_time,
738 monotonic_remote_now)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700739 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -0800740 << state->remote_node(timestamped_message.channel_index)
741 ->name()
742 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -0800743 << " while trying to send a message on "
744 << configuration::CleanedChannelToString(
745 logged_configuration()->channels()->Get(
746 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700747 << " " << state->DebugString();
Austin Schuh58646e22021-08-23 23:51:46 -0700748 } else if (monotonic_remote_now.boot !=
749 timestamped_message.monotonic_remote_time.boot) {
750 LOG(WARNING) << "Missmatched boots, " << monotonic_remote_now.boot
751 << " vs "
752 << timestamped_message.monotonic_remote_time.boot;
753 } else if (timestamped_message.monotonic_remote_time >
754 monotonic_remote_now) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700755 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -0800756 << "Check failed: timestamped_message.monotonic_remote_time < "
757 "state->monotonic_remote_now(timestamped_message.channel_"
758 "index) ("
759 << timestamped_message.monotonic_remote_time << " vs. "
760 << state->monotonic_remote_now(
761 timestamped_message.channel_index)
762 << ") " << state->event_loop()->node()->name()->string_view()
763 << " to "
764 << state->remote_node(timestamped_message.channel_index)
765 ->name()
766 ->string_view()
767 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -0700768 << " ("
769 << state->ToDistributedClock(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700770 timestamped_message.monotonic_event_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700771 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -0800772 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -0700773 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -0800774 timestamped_message.channel_index,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700775 timestamped_message.monotonic_remote_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700776 << ") " << state->DebugString();
777 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800778 }
779
Austin Schuh15649d62019-12-28 16:36:38 -0800780 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700781 state->SetRealtimeOffset(timestamped_message.monotonic_event_time.time,
Austin Schuh287d43d2020-12-04 20:19:33 -0800782 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800783
Austin Schuh2f8fd752020-09-01 22:38:28 -0700784 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -0800785 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700786 // TODO(austin): std::move channel_data in and make that efficient in
787 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -0800788 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -0800789 } else if (!ignore_missing_data_ &&
Austin Schuh5ee56872021-01-30 16:53:34 -0800790 // When starting up, we can have data which was sent before the
791 // log starts, but the timestamp was after the log starts. This
792 // is unreasonable to avoid, so ignore the missing data.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700793 timestamped_message.monotonic_remote_time.time >=
Austin Schuh5ee56872021-01-30 16:53:34 -0800794 state->monotonic_remote_start_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700795 timestamped_message.monotonic_remote_time.boot,
Austin Schuh5ee56872021-01-30 16:53:34 -0800796 timestamped_message.channel_index) &&
Austin Schuhdda74ec2021-01-03 19:30:37 -0800797 !FLAGS_skip_missing_forwarding_entries) {
Austin Schuh5ee56872021-01-30 16:53:34 -0800798 // We've found a timestamp without data that we expect to have data for.
799 // This likely means that we are at the end of the log file. Record it
800 // and CHECK that in the rest of the log file, we don't find any more
801 // data on that channel. Not all channels will end at the same point in
802 // time since they can be in different files.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800803 VLOG(1) << "Found the last message on channel "
Austin Schuh94526302021-04-28 22:46:34 -0700804 << timestamped_message.channel_index << ", "
805 << configuration::CleanedChannelToString(
806 logged_configuration()->channels()->Get(
Austin Schuh58646e22021-08-23 23:51:46 -0700807 timestamped_message.channel_index))
808 << " " << timestamped_message;
Austin Schuhdda74ec2021-01-03 19:30:37 -0800809
Austin Schuh2bb80e02021-03-20 21:46:17 -0700810 // The user might be working with log files from 1 node but forgot to
811 // configure the infrastructure to log data for a remote channel on that
812 // node. That can be very hard to debug, even though the log reader is
813 // doing the right thing. At least log a warning in that case and tell
814 // the user what is happening so they can either update their config to
815 // log the channel or can find a log with the data.
816 {
817 const std::vector<std::string> logger_nodes =
818 FindLoggerNodes(log_files_);
819 if (logger_nodes.size()) {
820 // We have old logs which don't have the logger nodes logged. In
821 // that case, we can't be helpful :(
822 bool data_logged = false;
823 const Channel *channel = logged_configuration()->channels()->Get(
824 timestamped_message.channel_index);
825 for (const std::string &node : logger_nodes) {
826 data_logged |=
827 configuration::ChannelMessageIsLoggedOnNode(channel, node);
828 }
829 if (!data_logged) {
830 LOG(WARNING) << "Got a timestamp without any logfiles which "
831 "could contain data for channel "
832 << configuration::CleanedChannelToString(channel);
833 LOG(WARNING) << "Only have logs logged on ["
834 << absl::StrJoin(logger_nodes, ", ") << "]";
835 LOG(WARNING)
836 << "Dropping the rest of the data on "
837 << state->event_loop()->node()->name()->string_view();
838 LOG(WARNING)
839 << "Consider using --skip_missing_forwarding_entries to "
840 "bypass this, update your config to log it, or add data "
841 "from one of the nodes it is logged on.";
842 }
843 }
844 }
845
Austin Schuhdda74ec2021-01-03 19:30:37 -0800846 // Vector storing if we've seen a nullptr message or not per channel.
847 std::vector<bool> last_message;
848 last_message.resize(logged_configuration()->channels()->size(), false);
849
850 last_message[timestamped_message.channel_index] = true;
851
852 // Now that we found the end of one channel, artificially stop the
853 // rest. It is confusing when part of your data gets replayed but not
Austin Schuh5ee56872021-01-30 16:53:34 -0800854 // all. Read the rest of the messages and drop them on the floor while
855 // doing some basic validation.
Austin Schuh58646e22021-08-23 23:51:46 -0700856 while (state->OldestMessageTime() != BootTimestamp::max_time()) {
Austin Schuhb08891b2021-09-02 18:52:31 -0700857 // TODO(austin): This force queues up the rest of the log file for all
858 // the other nodes. We should do this through the timer instead to
859 // keep memory usage down.
Austin Schuhdda74ec2021-01-03 19:30:37 -0800860 TimestampedMessage next = state->PopOldest();
861 // Make sure that once we have seen the last message on a channel,
862 // data doesn't start back up again. If the user wants to play
863 // through events like this, they can set
864 // --skip_missing_forwarding_entries or ignore_missing_data_.
865 CHECK_LT(next.channel_index, last_message.size());
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700866 if (next.data == nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -0800867 last_message[next.channel_index] = true;
868 } else {
869 if (last_message[next.channel_index]) {
870 LOG(FATAL)
871 << "Found missing data in the middle of the log file on "
872 "channel "
Austin Schuh6e014b82021-09-14 17:46:33 -0700873 << next.channel_index << " "
874 << configuration::StrippedChannelToString(
875 logged_configuration()->channels()->Get(
876 next.channel_index))
877 << " " << next << " " << state->DebugString();
Austin Schuhdda74ec2021-01-03 19:30:37 -0800878 }
879 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800880 }
Austin Schuh92547522019-12-28 14:33:43 -0800881 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800882 } else {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700883 LOG(WARNING) << "Not sending data from before the start of the log file. "
884 << timestamped_message.monotonic_event_time.time
885 .time_since_epoch()
886 .count()
887 << " start "
888 << monotonic_start_time().time_since_epoch().count() << " "
Tyler Chatowb7c6eba2021-07-28 14:43:23 -0700889 << *timestamped_message.data;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800890 }
891
Austin Schuh58646e22021-08-23 23:51:46 -0700892 const BootTimestamp next_time = state->OldestMessageTime();
893 if (next_time != BootTimestamp::max_time()) {
894 if (next_time.boot != state->boot_count()) {
895 VLOG(1) << "Next message for "
896 << MaybeNodeName(state->event_loop()->node())
897 << "is on the next boot, " << next_time << " now is "
898 << state->monotonic_now();
899 CHECK(event_loop_factory_);
900 state->RunOnEnd();
901 return;
902 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700903 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
Austin Schuh58646e22021-08-23 23:51:46 -0700904 << "wakeup for " << next_time.time << "("
905 << state->ToDistributedClock(next_time.time)
Austin Schuh2f8fd752020-09-01 22:38:28 -0700906 << " distributed), now is " << state->monotonic_now();
Austin Schuh58646e22021-08-23 23:51:46 -0700907 state->Setup(next_time.time);
James Kuszmaul314f1672020-01-03 20:02:08 -0800908 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700909 VLOG(1) << MaybeNodeName(state->event_loop()->node())
910 << "No next message, scheduling shutdown";
Austin Schuh58646e22021-08-23 23:51:46 -0700911 state->RunOnEnd();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700912 // Set a timer up immediately after now to die. If we don't do this,
913 // then the senders waiting on the message we just read will never get
914 // called.
Austin Schuheecb9282020-01-08 17:43:30 -0800915 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700916 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
917 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -0800918 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800919 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800920
Austin Schuh2f8fd752020-09-01 22:38:28 -0700921 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
922 << state->event_loop()->context().monotonic_event_time << " now "
923 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -0700924 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -0800925
Austin Schuh58646e22021-08-23 23:51:46 -0700926 if (state->OldestMessageTime() != BootTimestamp::max_time()) {
927 state->set_startup_timer(
928 event_loop->AddTimer([state]() { state->RunOnStart(); }));
929 event_loop->OnRun([state]() {
930 BootTimestamp next_time = state->OldestMessageTime();
931 CHECK_EQ(next_time.boot, state->boot_count());
932 state->Setup(next_time.time);
933 state->SetupStartupTimer();
934 });
Austin Schuhe309d2a2019-11-29 13:25:21 -0800935 }
936}
937
938void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800939 // Make sure that things get destroyed in the correct order, rather than
940 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -0800941 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700942 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800943 }
Austin Schuh92547522019-12-28 14:33:43 -0800944
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800945 event_loop_factory_unique_ptr_.reset();
946 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800947}
948
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800949void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -0800950 std::string_view add_prefix,
951 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800952 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
953 const Channel *const channel = logged_configuration()->channels()->Get(ii);
954 if (channel->name()->str() == name &&
955 channel->type()->string_view() == type) {
956 CHECK_EQ(0u, remapped_channels_.count(ii))
957 << "Already remapped channel "
958 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -0800959 RemappedChannel remapped_channel;
960 remapped_channel.remapped_name =
961 std::string(add_prefix) + std::string(name);
962 remapped_channel.new_type = new_type;
963 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800964 VLOG(1) << "Remapping channel "
965 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -0800966 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -0800967 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800968 return;
969 }
970 }
971 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
972 << type;
973}
974
Austin Schuh01b4c352020-09-21 23:09:39 -0700975void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
976 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -0800977 std::string_view add_prefix,
978 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -0700979 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
980 const Channel *remapped_channel =
981 configuration::GetChannel(logged_configuration(), name, type, "", node);
982 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
983 << "\", \"type\": \"" << type << "\"}";
984 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
985 << "\"}";
986 VLOG(1) << "Remapped "
987 << aos::configuration::StrippedChannelToString(remapped_channel);
988
989 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
990 // we want it to degrade if the heuristics fail to just work.
991 //
992 // The easiest way to do this is going to be incredibly specific and verbose.
993 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
994 // /original/0/spray. Then, create a map from /original/spray to
995 // /original/0/spray for just the type we were asked for.
996 if (name != remapped_channel->name()->string_view()) {
997 MapT new_map;
998 new_map.match = std::make_unique<ChannelT>();
999 new_map.match->name = absl::StrCat(add_prefix, name);
1000 new_map.match->type = type;
1001 if (node != nullptr) {
1002 new_map.match->source_node = node->name()->str();
1003 }
1004 new_map.rename = std::make_unique<ChannelT>();
1005 new_map.rename->name =
1006 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1007 maps_.emplace_back(std::move(new_map));
1008 }
1009
1010 const size_t channel_index =
1011 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1012 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1013 << "Already remapped channel "
1014 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001015
1016 RemappedChannel remapped_channel_struct;
1017 remapped_channel_struct.remapped_name =
1018 std::string(add_prefix) +
1019 std::string(remapped_channel->name()->string_view());
1020 remapped_channel_struct.new_type = new_type;
1021 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001022 MakeRemappedConfig();
1023}
1024
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001025void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001026 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001027 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001028 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001029 << ": Can't change the mapping after the events are scheduled.";
1030 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001031 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001032
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001033 // If no remapping occurred and we are using the original config, then there
1034 // is nothing interesting to do here.
1035 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001036 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001037 return;
1038 }
1039 // Config to copy Channel definitions from. Use the specified
1040 // replay_configuration_ if it has been provided.
1041 const Configuration *const base_config = replay_configuration_ == nullptr
1042 ? logged_configuration()
1043 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001044
1045 // Create a config with all the channels, but un-sorted/merged. Collect up
1046 // the schemas while we do this. Call MergeConfiguration to sort everything,
1047 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001048
1049 // This is the builder that we use for the config containing all the new
1050 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001051 flatbuffers::FlatBufferBuilder fbb;
1052 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001053 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001054
1055 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1056 << ": Merging logic needs to be updated when the number of channel "
1057 "fields changes.";
1058
1059 // List of schemas.
1060 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1061 // Make sure our new RemoteMessage schema is in there for old logs without it.
1062 schema_map.insert(std::make_pair(
1063 RemoteMessage::GetFullyQualifiedName(),
1064 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1065 message_bridge::RemoteMessageSchema()))));
1066
1067 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001068 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001069 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001070 base_config, logged_configuration()->channels()->Get(pair.first), "",
1071 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001072 channel_offsets.emplace_back(
1073 CopyChannel(c, pair.second.remapped_name, "", &fbb));
Austin Schuh006a9f52021-04-07 16:24:18 -07001074
1075 if (c->has_destination_nodes()) {
1076 for (const Connection *connection : *c->destination_nodes()) {
1077 switch (connection->timestamp_logger()) {
1078 case LoggerConfig::LOCAL_LOGGER:
1079 case LoggerConfig::NOT_LOGGED:
1080 // There is no timestamp channel associated with this, so ignore it.
1081 break;
1082
1083 case LoggerConfig::REMOTE_LOGGER:
1084 case LoggerConfig::LOCAL_AND_REMOTE_LOGGER:
1085 // We want to make a split timestamp channel regardless of what type
1086 // of log this used to be. No sense propagating the single
1087 // timestamp channel.
1088
1089 CHECK(connection->has_timestamp_logger_nodes());
1090 for (const flatbuffers::String *timestamp_logger_node :
1091 *connection->timestamp_logger_nodes()) {
1092 const Node *node = configuration::GetNode(
1093 logged_configuration(), timestamp_logger_node->string_view());
1094 message_bridge::ChannelTimestampFinder finder(
1095 logged_configuration(), "log_reader", node);
1096
1097 // We are assuming here that all the maps are setup correctly to
1098 // handle arbitrary timestamps. Apply the maps for this node to
1099 // see what name this ends up with.
1100 std::string name = finder.SplitChannelName(
1101 pair.second.remapped_name, c->type()->str(), connection);
1102 std::string unmapped_name = name;
1103 configuration::HandleMaps(logged_configuration()->maps(), &name,
1104 "aos.message_bridge.RemoteMessage",
1105 node);
1106 CHECK_NE(name, unmapped_name)
1107 << ": Remote timestamp channel was not remapped, this is "
1108 "very fishy";
1109 flatbuffers::Offset<flatbuffers::String> channel_name_offset =
1110 fbb.CreateString(name);
1111 flatbuffers::Offset<flatbuffers::String> channel_type_offset =
1112 fbb.CreateString("aos.message_bridge.RemoteMessage");
1113 flatbuffers::Offset<flatbuffers::String> source_node_offset =
1114 fbb.CreateString(timestamp_logger_node->string_view());
1115
1116 // Now, build a channel. Don't log it, 2 senders, and match the
1117 // source frequency.
1118 Channel::Builder channel_builder(fbb);
1119 channel_builder.add_name(channel_name_offset);
1120 channel_builder.add_type(channel_type_offset);
1121 channel_builder.add_source_node(source_node_offset);
1122 channel_builder.add_logger(LoggerConfig::NOT_LOGGED);
1123 channel_builder.add_num_senders(2);
1124 if (c->has_frequency()) {
1125 channel_builder.add_frequency(c->frequency());
1126 }
1127 channel_offsets.emplace_back(channel_builder.Finish());
1128 }
1129 break;
1130 }
1131 }
1132 }
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001133 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001134
Austin Schuh0de30f32020-12-06 12:44:28 -08001135 // Now reconstruct the original channels, translating types as needed
1136 for (const Channel *c : *base_config->channels()) {
1137 // Search for a mapping channel.
1138 std::string_view new_type = "";
1139 for (auto &pair : remapped_channels_) {
1140 const Channel *const remapped_channel =
1141 logged_configuration()->channels()->Get(pair.first);
1142 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1143 remapped_channel->type()->string_view() == c->type()->string_view()) {
1144 new_type = pair.second.new_type;
1145 break;
1146 }
1147 }
1148
1149 // Copy everything over.
1150 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1151
1152 // Add the schema if it doesn't exist.
1153 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1154 CHECK(c->has_schema());
1155 schema_map.insert(std::make_pair(c->type()->string_view(),
1156 RecursiveCopyFlatBuffer(c->schema())));
1157 }
1158 }
1159
1160 // The MergeConfiguration API takes a vector, not a map. Convert.
1161 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1162 while (!schema_map.empty()) {
1163 schemas.emplace_back(std::move(schema_map.begin()->second));
1164 schema_map.erase(schema_map.begin());
1165 }
1166
1167 // Create the Configuration containing the new channels that we want to add.
1168 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1169 channels_offset =
1170 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1171
1172 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001173 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001174 if (base_config->maps()) {
1175 for (const Map *map : *base_config->maps()) {
1176 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1177 }
1178 }
1179
1180 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001181 for (const MapT &map : maps_) {
1182 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001183 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001184 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001185 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001186 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001187 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001188 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1189 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001190 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001191 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001192 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001193 match_builder.add_name(match_name_offset);
1194 match_builder.add_type(match_type_offset);
1195 if (!map.match->source_node.empty()) {
1196 match_builder.add_source_node(match_source_node_offset);
1197 }
1198 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1199
Austin Schuh0de30f32020-12-06 12:44:28 -08001200 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001201 rename_builder.add_name(rename_name_offset);
1202 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1203
Austin Schuh0de30f32020-12-06 12:44:28 -08001204 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001205 map_builder.add_match(match_offset);
1206 map_builder.add_rename(rename_offset);
1207 map_offsets.emplace_back(map_builder.Finish());
1208 }
1209
Austin Schuh0de30f32020-12-06 12:44:28 -08001210 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1211 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001212
Austin Schuh0de30f32020-12-06 12:44:28 -08001213 // And copy everything else over.
1214 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1215 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1216
1217 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1218 applications_offset =
1219 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1220
1221 // Now insert everything else in unmodified.
1222 ConfigurationBuilder configuration_builder(fbb);
1223 if (!channels_offset.IsNull()) {
1224 configuration_builder.add_channels(channels_offset);
1225 }
1226 if (!maps_offsets.IsNull()) {
1227 configuration_builder.add_maps(maps_offsets);
1228 }
1229 if (!nodes_offset.IsNull()) {
1230 configuration_builder.add_nodes(nodes_offset);
1231 }
1232 if (!applications_offset.IsNull()) {
1233 configuration_builder.add_applications(applications_offset);
1234 }
1235
1236 if (base_config->has_channel_storage_duration()) {
1237 configuration_builder.add_channel_storage_duration(
1238 base_config->channel_storage_duration());
1239 }
1240
1241 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1242 << ": Merging logic needs to be updated when the number of configuration "
1243 "fields changes.";
1244
1245 fbb.Finish(configuration_builder.Finish());
1246
1247 // Clean it up and return it! By using MergeConfiguration here, we'll
1248 // actually get a deduplicated config for free too.
1249 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1250 configuration::MergeConfiguration(
1251 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1252
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001253 remapped_configuration_buffer_ =
1254 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001255 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001256
1257 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001258
1259 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001260}
1261
Austin Schuh1c227352021-09-17 12:53:54 -07001262std::vector<const Channel *> LogReader::RemappedChannels() const {
1263 std::vector<const Channel *> result;
1264 result.reserve(remapped_channels_.size());
1265 for (auto &pair : remapped_channels_) {
1266 const Channel *const logged_channel =
1267 CHECK_NOTNULL(logged_configuration()->channels()->Get(pair.first));
1268
1269 auto channel_iterator = std::lower_bound(
1270 remapped_configuration_->channels()->cbegin(),
1271 remapped_configuration_->channels()->cend(),
1272 std::make_pair(std::string_view(pair.second.remapped_name),
1273 logged_channel->type()->string_view()),
1274 CompareChannels);
1275
1276 CHECK(channel_iterator != remapped_configuration_->channels()->cend());
1277 CHECK(EqualsChannels(
1278 *channel_iterator,
1279 std::make_pair(std::string_view(pair.second.remapped_name),
1280 logged_channel->type()->string_view())));
1281 result.push_back(*channel_iterator);
1282 }
1283 return result;
1284}
1285
Austin Schuh6f3babe2020-01-26 20:34:50 -08001286const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
Austin Schuh58646e22021-08-23 23:51:46 -07001287 const Node *node,
Austin Schuh6f3babe2020-01-26 20:34:50 -08001288 const Channel *channel) {
1289 std::string_view channel_name = channel->name()->string_view();
1290 std::string_view channel_type = channel->type()->string_view();
1291 const int channel_index =
1292 configuration::ChannelIndex(logged_configuration(), channel);
1293 // If the channel is remapped, find the correct channel name to use.
1294 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001295 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001296 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001297 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001298 }
1299
Austin Schuhee711052020-08-24 16:06:09 -07001300 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001301 const Channel *remapped_channel = configuration::GetChannel(
Austin Schuh58646e22021-08-23 23:51:46 -07001302 configuration(), channel_name, channel_type,
1303 event_loop ? event_loop->name() : "log_reader", node);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001304
1305 CHECK(remapped_channel != nullptr)
1306 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1307 << channel_type << "\"} because it is not in the provided configuration.";
1308
1309 return remapped_channel;
1310}
1311
Austin Schuh58646e22021-08-23 23:51:46 -07001312LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper,
1313 const Node *node)
1314 : timestamp_mapper_(std::move(timestamp_mapper)), node_(node) {}
Austin Schuh287d43d2020-12-04 20:19:33 -08001315
1316void LogReader::State::AddPeer(State *peer) {
1317 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1318 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1319 }
1320}
Austin Schuh858c9f32020-08-31 16:56:12 -07001321
Austin Schuh58646e22021-08-23 23:51:46 -07001322void LogReader::State::SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001323 NodeEventLoopFactory *node_event_loop_factory) {
1324 node_event_loop_factory_ = node_event_loop_factory;
Austin Schuh858c9f32020-08-31 16:56:12 -07001325}
1326
1327void LogReader::State::SetChannelCount(size_t count) {
1328 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001329 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001330 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001331 channel_source_state_.resize(count);
1332 factory_channel_index_.resize(count);
1333 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001334}
1335
Austin Schuh58646e22021-08-23 23:51:46 -07001336void LogReader::State::SetRemoteTimestampSender(
1337 size_t logged_channel_index, RemoteMessageSender *remote_timestamp_sender) {
1338 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1339}
1340
Austin Schuh858c9f32020-08-31 16:56:12 -07001341void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001342 size_t logged_channel_index, size_t factory_channel_index,
1343 std::unique_ptr<RawSender> sender,
Austin Schuh58646e22021-08-23 23:51:46 -07001344 message_bridge::NoncausalOffsetEstimator *filter, bool is_forwarded,
1345 State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001346 channels_[logged_channel_index] = std::move(sender);
1347 filters_[logged_channel_index] = filter;
Austin Schuh58646e22021-08-23 23:51:46 -07001348 channel_source_state_[logged_channel_index] = source_state;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001349
Austin Schuh58646e22021-08-23 23:51:46 -07001350 if (is_forwarded) {
1351 queue_index_map_[logged_channel_index] =
1352 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001353 }
1354
1355 factory_channel_index_[logged_channel_index] = factory_channel_index;
1356}
1357
Austin Schuh287d43d2020-12-04 20:19:33 -08001358bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1359 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh58646e22021-08-23 23:51:46 -07001360 CHECK(sender);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001361 uint32_t remote_queue_index = 0xffffffff;
1362
Austin Schuh287d43d2020-12-04 20:19:33 -08001363 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001364 State *source_state =
1365 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
Austin Schuh9942bae2021-01-07 22:06:44 -08001366 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh58646e22021-08-23 23:51:46 -07001367 source_state->queue_index_map_[timestamped_message.channel_index]
Austin Schuh287d43d2020-12-04 20:19:33 -08001368 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001369
Austin Schuh9942bae2021-01-07 22:06:44 -08001370 struct SentTimestamp {
1371 monotonic_clock::time_point monotonic_event_time;
1372 uint32_t queue_index;
1373 } search;
1374
Austin Schuh58646e22021-08-23 23:51:46 -07001375 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1376 source_state->boot_count());
Tyler Chatowbf0609c2021-07-31 16:13:27 -07001377 search.monotonic_event_time =
1378 timestamped_message.monotonic_remote_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001379 search.queue_index = timestamped_message.remote_queue_index.index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001380
1381 // Find the sent time if available.
1382 auto element = std::lower_bound(
1383 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001384 [](ContiguousSentTimestamp a, SentTimestamp b) {
1385 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001386 return true;
1387 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001388 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001389 return false;
1390 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001391
1392 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001393 return true;
1394 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001395 if (a.starting_queue_index >= b.queue_index) {
1396 return false;
1397 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001398
Austin Schuh9942bae2021-01-07 22:06:44 -08001399 // If it isn't clearly below or above, it is below. Since we return
1400 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001401 return false;
1402 });
1403
1404 // TODO(austin): Be a bit more principled here, but we will want to do that
1405 // after the logger rewrite. We hit this when one node finishes, but the
1406 // other node isn't done yet. So there is no send time, but there is a
1407 // receive time.
1408 if (element != queue_index_map->end()) {
Austin Schuh58646e22021-08-23 23:51:46 -07001409 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1410 source_state->boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001411
1412 CHECK_GE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001413 element->starting_monotonic_event_time);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001414 CHECK_LE(timestamped_message.monotonic_remote_time.time,
Austin Schuh9942bae2021-01-07 22:06:44 -08001415 element->ending_monotonic_event_time);
Austin Schuh58646e22021-08-23 23:51:46 -07001416 CHECK_GE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001417 element->starting_queue_index);
Austin Schuh58646e22021-08-23 23:51:46 -07001418 CHECK_LE(timestamped_message.remote_queue_index.index,
Austin Schuh9942bae2021-01-07 22:06:44 -08001419 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001420
Austin Schuh58646e22021-08-23 23:51:46 -07001421 remote_queue_index = timestamped_message.remote_queue_index.index +
Austin Schuh9942bae2021-01-07 22:06:44 -08001422 element->actual_queue_index -
1423 element->starting_queue_index;
1424 } else {
1425 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001426 }
Austin Schuh58646e22021-08-23 23:51:46 -07001427 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1428 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001429 }
1430
1431 // Send! Use the replayed queue index here instead of the logged queue index
1432 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001433 const bool sent = sender->Send(
Tyler Chatowb7c6eba2021-07-28 14:43:23 -07001434 RawSender::SharedSpan(timestamped_message.data,
1435 &timestamped_message.data->span),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001436 timestamped_message.monotonic_remote_time.time,
Austin Schuh8902fa52021-03-14 22:39:24 -07001437 timestamped_message.realtime_remote_time, remote_queue_index,
1438 (channel_source_state_[timestamped_message.channel_index] != nullptr
1439 ? CHECK_NOTNULL(
1440 channel_source_state_[timestamped_message.channel_index])
1441 ->event_loop_->boot_uuid()
1442 : event_loop_->boot_uuid()));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001443 if (!sent) return false;
1444
Austin Schuh287d43d2020-12-04 20:19:33 -08001445 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh58646e22021-08-23 23:51:46 -07001446 CHECK_EQ(timestamped_message.monotonic_event_time.boot, boot_count());
Austin Schuh9942bae2021-01-07 22:06:44 -08001447 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1448 // Nothing here, start a range with 0 length.
1449 ContiguousSentTimestamp timestamp;
1450 timestamp.starting_monotonic_event_time =
1451 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001452 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001453 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001454 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001455 timestamp.actual_queue_index = sender->sent_queue_index();
1456 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1457 timestamp);
1458 } else {
1459 // We've got something. See if the next timestamp is still contiguous. If
1460 // so, grow it.
1461 ContiguousSentTimestamp *back =
1462 &queue_index_map_[timestamped_message.channel_index]->back();
1463 if ((back->starting_queue_index - back->actual_queue_index) ==
Austin Schuh58646e22021-08-23 23:51:46 -07001464 (timestamped_message.queue_index.index - sender->sent_queue_index())) {
1465 back->ending_queue_index = timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001466 back->ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001467 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001468 } else {
1469 // Otherwise, make a new one.
1470 ContiguousSentTimestamp timestamp;
1471 timestamp.starting_monotonic_event_time =
1472 timestamp.ending_monotonic_event_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001473 timestamped_message.monotonic_event_time.time;
Austin Schuh9942bae2021-01-07 22:06:44 -08001474 timestamp.starting_queue_index = timestamp.ending_queue_index =
Austin Schuh58646e22021-08-23 23:51:46 -07001475 timestamped_message.queue_index.index;
Austin Schuh9942bae2021-01-07 22:06:44 -08001476 timestamp.actual_queue_index = sender->sent_queue_index();
1477 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1478 timestamp);
1479 }
1480 }
1481
1482 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1483 // queue index diverge a couple of elements, which would be a very small
1484 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001485 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1486 nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001487 State *source_state =
1488 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index]);
1489
Austin Schuh969cd602021-01-03 00:09:45 -08001490 flatbuffers::FlatBufferBuilder fbb;
1491 fbb.ForceDefaults(true);
Austin Schuhcdd90272021-03-15 12:46:16 -07001492 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> boot_uuid_offset =
1493 event_loop_->boot_uuid().PackVector(&fbb);
Austin Schuh315b96b2020-12-11 21:21:12 -08001494
Austin Schuh969cd602021-01-03 00:09:45 -08001495 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001496
1497 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001498 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001499
1500 // Swap the remote and sent metrics. They are from the sender's
1501 // perspective, not the receiver's perspective.
1502 message_header_builder.add_monotonic_sent_time(
1503 sender->monotonic_sent_time().time_since_epoch().count());
1504 message_header_builder.add_realtime_sent_time(
1505 sender->realtime_sent_time().time_since_epoch().count());
1506 message_header_builder.add_queue_index(sender->sent_queue_index());
1507
Austin Schuh58646e22021-08-23 23:51:46 -07001508 CHECK_EQ(timestamped_message.monotonic_remote_time.boot,
1509 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001510 message_header_builder.add_monotonic_remote_time(
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001511 timestamped_message.monotonic_remote_time.time.time_since_epoch()
1512 .count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001513 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001514 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001515
1516 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001517 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001518
Austin Schuh969cd602021-01-03 00:09:45 -08001519 fbb.Finish(message_header_builder.Finish());
1520
1521 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1522 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
Austin Schuh58646e22021-08-23 23:51:46 -07001523 timestamped_message.monotonic_timestamp_time,
1524 source_state->boot_count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001525 }
1526
1527 return true;
1528}
1529
Austin Schuh969cd602021-01-03 00:09:45 -08001530LogReader::RemoteMessageSender::RemoteMessageSender(
1531 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1532 : event_loop_(event_loop),
1533 sender_(std::move(sender)),
1534 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
1535
1536void LogReader::RemoteMessageSender::ScheduleTimestamp() {
1537 if (remote_timestamps_.empty()) {
1538 CHECK_NOTNULL(timer_);
1539 timer_->Disable();
1540 scheduled_time_ = monotonic_clock::min_time;
1541 return;
1542 }
1543
1544 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
1545 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08001546 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08001547 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
Austin Schuh3d94be02021-02-12 23:15:20 -08001548 CHECK_GE(scheduled_time_, event_loop_->monotonic_now())
1549 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001550 }
1551}
1552
1553void LogReader::RemoteMessageSender::Send(
1554 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
Austin Schuh58646e22021-08-23 23:51:46 -07001555 BootTimestamp monotonic_timestamp_time, size_t source_boot_count) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001556 // There are 2 variants of logs.
1557 // 1) Logs without monotonic_timestamp_time
1558 // 2) Logs with monotonic_timestamp_time
1559 //
1560 // As of Jan 2021, we shouldn't have any more logs without
1561 // monotonic_timestamp_time. We don't have data locked up in those logs worth
1562 // the effort of saving.
1563 //
1564 // This gives us 3 cases, 2 of which are undistinguishable.
1565 // 1) Old log without monotonic_timestamp_time.
1566 // 2) New log with monotonic_timestamp_time where the timestamp was logged
1567 // remotely so we actually have monotonic_timestamp_time.
1568 // 3) New log, but the timestamp was logged on the node receiving the message
1569 // so there is no monotonic_timestamp_time.
1570 //
1571 // Our goal when replaying is to accurately reproduce the state of the world
1572 // present when logging. If a timestamp wasn't sent back across the network,
1573 // we shouldn't replay one back across the network.
1574 //
1575 // Given that we don't really care about 1, we can use the presence of the
1576 // timestamp to distinguish 2 and 3, and ignore 1. If we don't have a
1577 // monotonic_timestamp_time, this means the message was logged locally and
1578 // remote timestamps can be ignored.
Austin Schuh58646e22021-08-23 23:51:46 -07001579 if (monotonic_timestamp_time == BootTimestamp::min_time()) {
Austin Schuhc41d6a82021-07-16 14:49:23 -07001580 return;
Austin Schuh969cd602021-01-03 00:09:45 -08001581 }
Austin Schuhc41d6a82021-07-16 14:49:23 -07001582
Austin Schuh58646e22021-08-23 23:51:46 -07001583 CHECK_EQ(monotonic_timestamp_time.boot, source_boot_count);
1584
Austin Schuhc41d6a82021-07-16 14:49:23 -07001585 remote_timestamps_.emplace(
1586 std::upper_bound(
1587 remote_timestamps_.begin(), remote_timestamps_.end(),
Austin Schuh58646e22021-08-23 23:51:46 -07001588 monotonic_timestamp_time.time,
Austin Schuhc41d6a82021-07-16 14:49:23 -07001589 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
1590 const Timestamp &timestamp) {
1591 return monotonic_timestamp_time <
1592 timestamp.monotonic_timestamp_time;
1593 }),
Austin Schuh58646e22021-08-23 23:51:46 -07001594 std::move(remote_message), monotonic_timestamp_time.time);
Austin Schuhc41d6a82021-07-16 14:49:23 -07001595 ScheduleTimestamp();
Austin Schuh969cd602021-01-03 00:09:45 -08001596}
1597
1598void LogReader::RemoteMessageSender::SendTimestamp() {
Austin Schuh3d94be02021-02-12 23:15:20 -08001599 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_)
1600 << event_loop_->node()->name()->string_view();
Austin Schuh969cd602021-01-03 00:09:45 -08001601 CHECK(!remote_timestamps_.empty());
1602
1603 // Send out all timestamps at the currently scheduled time.
1604 while (remote_timestamps_.front().monotonic_timestamp_time ==
1605 scheduled_time_) {
1606 sender_.Send(std::move(remote_timestamps_.front().remote_message));
1607 remote_timestamps_.pop_front();
1608 if (remote_timestamps_.empty()) {
1609 break;
1610 }
1611 }
1612 scheduled_time_ = monotonic_clock::min_time;
1613
1614 ScheduleTimestamp();
1615}
1616
1617LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh61e973f2021-02-21 21:43:56 -08001618 const Channel *channel, const Connection *connection) {
1619 message_bridge::ChannelTimestampFinder finder(event_loop_);
1620 // Look at any pre-created channel/connection pairs.
1621 {
1622 auto it =
1623 channel_timestamp_loggers_.find(std::make_pair(channel, connection));
1624 if (it != channel_timestamp_loggers_.end()) {
1625 return it->second.get();
1626 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001627 }
1628
Austin Schuh61e973f2021-02-21 21:43:56 -08001629 // That failed, so resolve the RemoteMessage channel timestamps will be logged
1630 // to.
1631 const Channel *timestamp_channel = finder.ForChannel(channel, connection);
1632
1633 {
1634 // See if that has been created before. If so, cache it in
1635 // channel_timestamp_loggers_ and return.
1636 auto it = timestamp_loggers_.find(timestamp_channel);
1637 if (it != timestamp_loggers_.end()) {
1638 CHECK(channel_timestamp_loggers_
1639 .try_emplace(std::make_pair(channel, connection), it->second)
1640 .second);
1641 return it->second.get();
1642 }
1643 }
1644
1645 // Otherwise, make a sender, save it, and cache it.
1646 auto result = channel_timestamp_loggers_.try_emplace(
1647 std::make_pair(channel, connection),
1648 std::make_shared<RemoteMessageSender>(
1649 event_loop()->MakeSender<RemoteMessage>(
1650 timestamp_channel->name()->string_view()),
1651 event_loop()));
1652
1653 CHECK(timestamp_loggers_.try_emplace(timestamp_channel, result.first->second)
1654 .second);
1655 return result.first->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07001656}
1657
Austin Schuhdda74ec2021-01-03 19:30:37 -08001658TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08001659 CHECK(timestamp_mapper_ != nullptr);
1660 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1661 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07001662
Austin Schuhe639ea12021-01-25 13:00:22 -08001663 TimestampedMessage result = std::move(*result_ptr);
1664
Austin Schuh2f8fd752020-09-01 22:38:28 -07001665 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08001666 << result.monotonic_event_time;
1667 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07001668 SeedSortedMessages();
1669
Austin Schuh58646e22021-08-23 23:51:46 -07001670 CHECK_EQ(result.monotonic_event_time.boot, boot_count());
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001671
Austin Schuh5ee56872021-01-30 16:53:34 -08001672 VLOG(1) << "Popped " << result
1673 << configuration::CleanedChannelToString(
1674 event_loop_->configuration()->channels()->Get(
1675 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08001676 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07001677}
1678
Austin Schuh58646e22021-08-23 23:51:46 -07001679BootTimestamp LogReader::State::OldestMessageTime() const {
Austin Schuhe639ea12021-01-25 13:00:22 -08001680 if (timestamp_mapper_ == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001681 return BootTimestamp::max_time();
Austin Schuh287d43d2020-12-04 20:19:33 -08001682 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001683 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
1684 if (result_ptr == nullptr) {
Austin Schuh58646e22021-08-23 23:51:46 -07001685 return BootTimestamp::max_time();
Austin Schuhe639ea12021-01-25 13:00:22 -08001686 }
1687 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001688 << result_ptr->monotonic_event_time.time;
Austin Schuh58646e22021-08-23 23:51:46 -07001689 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001690}
1691
1692void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001693 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001694
Austin Schuhe639ea12021-01-25 13:00:22 -08001695 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
1696 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07001697}
1698
1699void LogReader::State::Deregister() {
Austin Schuh58646e22021-08-23 23:51:46 -07001700 if (started_ && !stopped_) {
1701 RunOnEnd();
1702 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001703 for (size_t i = 0; i < channels_.size(); ++i) {
1704 channels_[i].reset();
1705 }
Austin Schuh61e973f2021-02-21 21:43:56 -08001706 channel_timestamp_loggers_.clear();
1707 timestamp_loggers_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001708 event_loop_unique_ptr_.reset();
1709 event_loop_ = nullptr;
1710 timer_handler_ = nullptr;
1711 node_event_loop_factory_ = nullptr;
1712}
1713
Austin Schuhe309d2a2019-11-29 13:25:21 -08001714} // namespace logger
1715} // namespace aos