blob: 671fbeaececa3c5ed1748e0bc05b7ae9f869e425 [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.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>
8#include <vector>
9
Austin Schuh8bd96322020-02-13 21:18:22 -080010#include "Eigen/Dense"
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 Schuh64fab802020-09-09 22:47:47 -070016#include "aos/events/logging/uuid.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 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 Schuhe309d2a2019-11-29 13:25:21 -080024#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070025#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080026
Austin Schuh15649d62019-12-28 16:36:38 -080027DEFINE_bool(skip_missing_forwarding_entries, false,
28 "If true, drop any forwarding entries with missing data. If "
29 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080030
Austin Schuh0ca1fd32020-12-18 22:53:05 -080031DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080032
Austin Schuh2f8fd752020-09-01 22:38:28 -070033DEFINE_bool(skip_order_validation, false,
34 "If true, ignore any out of orderness in replay");
35
Austin Schuhe309d2a2019-11-29 13:25:21 -080036namespace aos {
37namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070038namespace {
39// Helper to safely read a header, or CHECK.
Austin Schuhadd6eb32020-11-09 21:24:26 -080040SizePrefixedFlatbufferVector<LogFileHeader> MaybeReadHeaderOrDie(
Austin Schuh287d43d2020-12-04 20:19:33 -080041 const std::vector<LogFile> &log_files) {
42 CHECK_GE(log_files.size(), 1u) << ": Empty filenames list";
43 CHECK_GE(log_files[0].parts.size(), 1u) << ": Empty filenames list";
44 CHECK_GE(log_files[0].parts[0].parts.size(), 1u) << ": Empty filenames list";
Austin Schuhadd6eb32020-11-09 21:24:26 -080045 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> result =
Austin Schuh287d43d2020-12-04 20:19:33 -080046 ReadHeader(log_files[0].parts[0].parts[0]);
Austin Schuh3bd4c402020-11-06 18:19:06 -080047 CHECK(result);
48 return result.value();
Austin Schuh0afc4d12020-10-19 11:42:04 -070049}
Austin Schuh0de30f32020-12-06 12:44:28 -080050
Austin Schuh315b96b2020-12-11 21:21:12 -080051std::string LogFileVectorToString(std::vector<LogFile> log_files) {
52 std::stringstream ss;
53 for (const auto f : log_files) {
54 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
Brian Silverman1f345222020-09-24 21:14:48 -0700123Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
124 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800125 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700126 configuration_(configuration),
127 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700128 timer_handler_(event_loop_->AddTimer(
129 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700130 server_statistics_fetcher_(
131 configuration::MultiNode(event_loop_->configuration())
132 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
133 "/aos")
134 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700135 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700136
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700137 // Find all the nodes which are logging timestamps on our node. This may
138 // over-estimate if should_log is specified.
139 std::vector<const Node *> timestamp_logger_nodes =
140 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700141
142 std::map<const Channel *, const Node *> timestamp_logger_channels;
143
144 // Now that we have all the nodes accumulated, make remote timestamp loggers
145 // for them.
146 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700147 // Note: since we are doing a find using the event loop channel, we need to
148 // make sure this channel pointer is part of the event loop configuration,
149 // not configuration_. This only matters when configuration_ !=
150 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700151 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700152 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700153 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800154 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700155 event_loop_->node());
156
157 CHECK(channel != nullptr)
158 << ": Remote timestamps are logged on "
159 << event_loop_->node()->name()->string_view()
160 << " but can't find channel /aos/remote_timestamps/"
161 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700162 if (!should_log(channel)) {
163 continue;
164 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700165 timestamp_logger_channels.insert(std::make_pair(channel, node));
166 }
167
Brian Silvermand90905f2020-09-23 14:42:56 -0700168 const size_t our_node_index =
169 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700170
Brian Silverman1f345222020-09-24 21:14:48 -0700171 for (size_t channel_index = 0;
172 channel_index < configuration_->channels()->size(); ++channel_index) {
173 const Channel *const config_channel =
174 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700175 // The MakeRawFetcher method needs a channel which is in the event loop
176 // configuration() object, not the configuration_ object. Go look that up
177 // from the config.
178 const Channel *channel = aos::configuration::GetChannel(
179 event_loop_->configuration(), config_channel->name()->string_view(),
180 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700181 CHECK(channel != nullptr)
182 << ": Failed to look up channel "
183 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700184 if (!should_log(channel)) {
185 continue;
186 }
Austin Schuh0c297012020-09-16 18:41:59 -0700187
Austin Schuhe309d2a2019-11-29 13:25:21 -0800188 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700189 fs.channel_index = channel_index;
190 fs.channel = channel;
191
Austin Schuh6f3babe2020-01-26 20:34:50 -0800192 const bool is_local =
193 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
194
Austin Schuh15649d62019-12-28 16:36:38 -0800195 const bool is_readable =
196 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700197 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
198 channel, event_loop_->node());
199 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800200
Brian Silverman1f345222020-09-24 21:14:48 -0700201 bool log_delivery_times = false;
202 if (event_loop_->node() != nullptr) {
203 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
204 channel, event_loop_->node(), event_loop_->node());
205 }
Austin Schuh15649d62019-12-28 16:36:38 -0800206
Austin Schuh0de30f32020-12-06 12:44:28 -0800207 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700208 // contents to a file directly.
209 const bool log_contents = timestamp_logger_channels.find(channel) !=
210 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700211
212 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800213 fs.fetcher = event_loop->MakeRawFetcher(channel);
214 VLOG(1) << "Logging channel "
215 << configuration::CleanedChannelToString(channel);
216
217 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800218 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700219 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800220 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800221 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800222 if (log_message) {
223 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700224 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800225 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800226 const Node *source_node = configuration::GetNode(
227 configuration_, channel->source_node()->string_view());
228 fs.data_node_index =
229 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800230 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800231 } else {
232 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800233 }
234 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700235 if (log_contents) {
236 VLOG(1) << "Timestamp logger channel "
237 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700238 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
239 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800240 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700241 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700242 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800243 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800244 }
Brian Silverman1f345222020-09-24 21:14:48 -0700245 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700246
247 // When we are logging remote timestamps, we need to be able to translate from
248 // the channel index that the event loop uses to the channel index in the
249 // config in the log file.
250 event_loop_to_logged_channel_index_.resize(
251 event_loop->configuration()->channels()->size(), -1);
252 for (size_t event_loop_channel_index = 0;
253 event_loop_channel_index <
254 event_loop->configuration()->channels()->size();
255 ++event_loop_channel_index) {
256 const Channel *event_loop_channel =
257 event_loop->configuration()->channels()->Get(event_loop_channel_index);
258
259 const Channel *logged_channel = aos::configuration::GetChannel(
260 configuration_, event_loop_channel->name()->string_view(),
261 event_loop_channel->type()->string_view(), "",
262 configuration::GetNode(configuration_, event_loop_->node()));
263
264 if (logged_channel != nullptr) {
265 event_loop_to_logged_channel_index_[event_loop_channel_index] =
266 configuration::ChannelIndex(configuration_, logged_channel);
267 }
268 }
Brian Silverman1f345222020-09-24 21:14:48 -0700269}
270
271Logger::~Logger() {
272 if (log_namer_) {
273 // If we are replaying a log file, or in simulation, we want to force the
274 // last bit of data to be logged. The easiest way to deal with this is to
275 // poll everything as we go to destroy the class, ie, shut down the logger,
276 // and write it to disk.
277 StopLogging(event_loop_->monotonic_now());
278 }
279}
280
Brian Silvermanae7c0332020-09-30 16:58:23 -0700281void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
282 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700283 CHECK(!log_namer_) << ": Already logging";
284 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700285 log_event_uuid_ = UUID::Random();
286 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700287 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
288
289 // We want to do as much work as possible before the initial Fetch. Time
290 // between that and actually starting to log opens up the possibility of
291 // falling off the end of the queue during that time.
292
293 for (FetcherStruct &f : fetchers_) {
294 if (f.wants_writer) {
295 f.writer = log_namer_->MakeWriter(f.channel);
296 }
297 if (f.wants_timestamp_writer) {
298 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
299 }
300 if (f.wants_contents_writer) {
301 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
302 f.channel, CHECK_NOTNULL(f.timestamp_node));
303 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800304 }
305
Brian Silverman1f345222020-09-24 21:14:48 -0700306 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700307 node_state_.resize(configuration::MultiNode(configuration_)
308 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700309 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800310
Austin Schuh2f8fd752020-09-01 22:38:28 -0700311 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700312 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800313
Austin Schuh2f8fd752020-09-01 22:38:28 -0700314 node_state_[node_index].log_file_header = MakeHeader(node);
315 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800316
Austin Schuh2f8fd752020-09-01 22:38:28 -0700317 // Grab data from each channel right before we declare the log file started
318 // so we can capture the latest message on each channel. This lets us have
319 // non periodic messages with configuration that now get logged.
320 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700321 const auto start = event_loop_->monotonic_now();
322 const bool got_new = f.fetcher->Fetch();
323 const auto end = event_loop_->monotonic_now();
324 RecordFetchResult(start, end, got_new, &f);
325
326 // If there is a message, we want to write it.
327 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700328 }
329
330 // Clear out any old timestamps in case we are re-starting logging.
331 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800332 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
333 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700334 }
335
336 WriteHeader();
337
338 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
339 << " start_time " << last_synchronized_time_;
340
Austin Schuh315b96b2020-12-11 21:21:12 -0800341 // Force logging up until the start of the log file now, so the messages at
342 // the start are always ordered before the rest of the messages.
343 // Note: this ship may have already sailed, but we don't have to make it
344 // worse.
345 // TODO(austin): Test...
346 LogUntil(last_synchronized_time_);
347
Austin Schuh2f8fd752020-09-01 22:38:28 -0700348 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
349 polling_period_);
350}
351
Brian Silverman1f345222020-09-24 21:14:48 -0700352std::unique_ptr<LogNamer> Logger::StopLogging(
353 aos::monotonic_clock::time_point end_time) {
354 CHECK(log_namer_) << ": Not logging right now";
355
356 if (end_time != aos::monotonic_clock::min_time) {
357 LogUntil(end_time);
358 }
359 timer_handler_->Disable();
360
361 for (FetcherStruct &f : fetchers_) {
362 f.writer = nullptr;
363 f.timestamp_writer = nullptr;
364 f.contents_writer = nullptr;
365 }
366 node_state_.clear();
367
Brian Silvermanae7c0332020-09-30 16:58:23 -0700368 log_event_uuid_ = UUID::Zero();
369 log_start_uuid_ = std::string();
370
Brian Silverman1f345222020-09-24 21:14:48 -0700371 return std::move(log_namer_);
372}
373
Austin Schuhfa895892020-01-07 20:07:41 -0800374void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700375 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700376 server_statistics_fetcher_.Fetch();
377 }
378
379 aos::monotonic_clock::time_point monotonic_start_time =
380 event_loop_->monotonic_now();
381 aos::realtime_clock::time_point realtime_start_time =
382 event_loop_->realtime_now();
383
384 // We need to pick a point in time to declare the log file "started". This
385 // starts here. It needs to be after everything is fetched so that the
386 // fetchers are all pointed at the most recent message before the start
387 // time.
388 last_synchronized_time_ = monotonic_start_time;
389
Austin Schuh6f3babe2020-01-26 20:34:50 -0800390 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700391 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700392 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
393 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800394 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800395 }
396}
Austin Schuh8bd96322020-02-13 21:18:22 -0800397
Austin Schuh315b96b2020-12-11 21:21:12 -0800398void Logger::MaybeWriteHeader(int node_index) {
399 if (configuration::MultiNode(configuration_)) {
400 return MaybeWriteHeader(node_index,
401 configuration_->nodes()->Get(node_index));
402 } else {
403 return MaybeWriteHeader(node_index, nullptr);
404 }
405}
406
407void Logger::MaybeWriteHeader(int node_index, const Node *node) {
408 // This function is responsible for writing the header when the header both
409 // has valid data, and when it needs to be written.
410 if (node_state_[node_index].header_written &&
411 node_state_[node_index].header_valid) {
412 // The header has been written and is valid, nothing to do.
413 return;
414 }
415 if (!node_state_[node_index].has_source_node_boot_uuid) {
416 // Can't write a header if we don't have the boot UUID.
417 return;
418 }
419
420 // WriteHeader writes the first header in a log file. We want to do this only
421 // once.
422 //
423 // Rotate rewrites the same header with a new part ID, but keeps the same part
424 // UUID. We don't want that when things reboot, because that implies that
425 // parts go together across a reboot.
426 //
427 // Reboot resets the parts UUID. So, once we've written a header the first
428 // time, we want to use Reboot to rotate the log and reset the parts UUID.
429 //
430 // header_valid is cleared whenever the remote reboots.
431 if (node_state_[node_index].header_written) {
432 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
433 } else {
434 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
435
436 node_state_[node_index].header_written = true;
437 }
438 node_state_[node_index].header_valid = true;
439}
440
Austin Schuh2f8fd752020-09-01 22:38:28 -0700441void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700442 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700443 server_statistics_fetcher_.Fetch();
444 } else {
445 return;
446 }
447
448 if (server_statistics_fetcher_.get() == nullptr) {
449 return;
450 }
451
452 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700453 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700454 if (MaybeUpdateTimestamp(
455 node, node_index,
456 server_statistics_fetcher_.context().monotonic_event_time,
457 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800458 CHECK(node_state_[node_index].header_written);
459 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700460 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800461 } else {
462 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463 }
464 }
465}
466
Austin Schuh315b96b2020-12-11 21:21:12 -0800467void Logger::SetStartTime(
468 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
469 aos::realtime_clock::time_point realtime_start_time,
470 aos::monotonic_clock::time_point logger_monotonic_start_time,
471 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700472 node_state_[node_index].monotonic_start_time = monotonic_start_time;
473 node_state_[node_index].realtime_start_time = realtime_start_time;
474 node_state_[node_index]
475 .log_file_header.mutable_message()
476 ->mutate_monotonic_start_time(
477 std::chrono::duration_cast<std::chrono::nanoseconds>(
478 monotonic_start_time.time_since_epoch())
479 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800480
481 // Add logger start times if they are available in the log file header.
482 if (node_state_[node_index]
483 .log_file_header.mutable_message()
484 ->has_logger_monotonic_start_time()) {
485 node_state_[node_index]
486 .log_file_header.mutable_message()
487 ->mutate_logger_monotonic_start_time(
488 std::chrono::duration_cast<std::chrono::nanoseconds>(
489 logger_monotonic_start_time.time_since_epoch())
490 .count());
491 }
492
493 if (node_state_[node_index]
494 .log_file_header.mutable_message()
495 ->has_logger_realtime_start_time()) {
496 node_state_[node_index]
497 .log_file_header.mutable_message()
498 ->mutate_logger_realtime_start_time(
499 std::chrono::duration_cast<std::chrono::nanoseconds>(
500 logger_realtime_start_time.time_since_epoch())
501 .count());
502 }
503
Austin Schuh2f8fd752020-09-01 22:38:28 -0700504 if (node_state_[node_index]
505 .log_file_header.mutable_message()
506 ->has_realtime_start_time()) {
507 node_state_[node_index]
508 .log_file_header.mutable_message()
509 ->mutate_realtime_start_time(
510 std::chrono::duration_cast<std::chrono::nanoseconds>(
511 realtime_start_time.time_since_epoch())
512 .count());
513 }
514}
515
516bool Logger::MaybeUpdateTimestamp(
517 const Node *node, int node_index,
518 aos::monotonic_clock::time_point monotonic_start_time,
519 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700520 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700521 if (node_state_[node_index].monotonic_start_time !=
522 monotonic_clock::min_time) {
523 return false;
524 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800525 if (event_loop_->node() == node ||
526 !configuration::MultiNode(configuration_)) {
527 // There are no offsets to compute for ourself, so always succeed.
528 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
529 monotonic_start_time, realtime_start_time);
530 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700531 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800532 } else if (server_statistics_fetcher_.get() != nullptr) {
533 // We must be a remote node now. Look for the connection and see if it is
534 // connected.
535
536 for (const message_bridge::ServerConnection *connection :
537 *server_statistics_fetcher_->connections()) {
538 if (connection->node()->name()->string_view() !=
539 node->name()->string_view()) {
540 continue;
541 }
542
543 if (connection->state() != message_bridge::State::CONNECTED) {
544 VLOG(1) << node->name()->string_view()
545 << " is not connected, can't start it yet.";
546 break;
547 }
548
549 // Update the boot UUID as soon as we know we are connected.
550 if (!connection->has_boot_uuid()) {
551 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
552 break;
553 }
554
555 if (!node_state_[node_index].has_source_node_boot_uuid ||
556 node_state_[node_index].source_node_boot_uuid !=
557 connection->boot_uuid()->string_view()) {
558 node_state_[node_index].SetBootUUID(
559 connection->boot_uuid()->string_view());
560 }
561
562 if (!connection->has_monotonic_offset()) {
563 VLOG(1) << "Missing monotonic offset for setting start time for node "
564 << aos::FlatbufferToJson(node);
565 break;
566 }
567
568 // Found it and it is connected. Compensate and go.
569 SetStartTime(node_index,
570 monotonic_start_time +
571 std::chrono::nanoseconds(connection->monotonic_offset()),
572 realtime_start_time, monotonic_start_time,
573 realtime_start_time);
574 return true;
575 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700576 }
577 return false;
578}
579
580aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
581 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800582 // Now write the header with this timestamp in it.
583 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800584 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800585
Austin Schuh2f8fd752020-09-01 22:38:28 -0700586 // TODO(austin): Compress this much more efficiently. There are a bunch of
587 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700588 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700589 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800590
Brian Silvermanae7c0332020-09-30 16:58:23 -0700591 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700592 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800593
Brian Silvermanae7c0332020-09-30 16:58:23 -0700594 CHECK(log_event_uuid_ != UUID::Zero());
595 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
596 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700597
Brian Silvermanae7c0332020-09-30 16:58:23 -0700598 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
599 fbb.CreateString(logger_instance_uuid_.string_view());
600
601 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
602 if (!log_start_uuid_.empty()) {
603 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
604 }
605
Austin Schuh315b96b2020-12-11 21:21:12 -0800606 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
607 fbb.CreateString(event_loop_->boot_uuid().string_view());
608
609 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
610 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700611
612 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700613 fbb.CreateString("00000000-0000-4000-8000-000000000000");
614
Austin Schuhfa895892020-01-07 20:07:41 -0800615 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700616 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700617
Austin Schuh0c297012020-09-16 18:41:59 -0700618 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800619 // TODO(austin): Reuse the node we just copied in above.
620 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
621 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800622 }
623
624 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
625
Austin Schuh64fab802020-09-09 22:47:47 -0700626 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800627
628 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800629 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800630 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700631 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800632 }
633
634 log_file_header_builder.add_configuration(configuration_offset);
635 // The worst case theoretical out of order is the polling period times 2.
636 // One message could get logged right after the boundary, but be for right
637 // before the next boundary. And the reverse could happen for another
638 // message. Report back 3x to be extra safe, and because the cost isn't
639 // huge on the read side.
640 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700641 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800642
643 log_file_header_builder.add_monotonic_start_time(
644 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700645 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800646 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700647 if (node == event_loop_->node()) {
648 log_file_header_builder.add_realtime_start_time(
649 std::chrono::duration_cast<std::chrono::nanoseconds>(
650 realtime_clock::min_time.time_since_epoch())
651 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800652 } else {
653 log_file_header_builder.add_logger_monotonic_start_time(
654 std::chrono::duration_cast<std::chrono::nanoseconds>(
655 monotonic_clock::min_time.time_since_epoch())
656 .count());
657 log_file_header_builder.add_logger_realtime_start_time(
658 std::chrono::duration_cast<std::chrono::nanoseconds>(
659 realtime_clock::min_time.time_since_epoch())
660 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800661 }
662
Brian Silvermanae7c0332020-09-30 16:58:23 -0700663 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
664 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
665 if (!log_start_uuid_offset.IsNull()) {
666 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
667 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800668 log_file_header_builder.add_logger_node_boot_uuid(
669 logger_node_boot_uuid_offset);
670 log_file_header_builder.add_source_node_boot_uuid(
671 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700672
673 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
674 log_file_header_builder.add_parts_index(0);
675
Austin Schuh2f8fd752020-09-01 22:38:28 -0700676 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800677 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
678 fbb.Release());
679
680 CHECK(result.Verify()) << ": Built a corrupted header.";
681
682 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700683}
684
Brian Silvermancb805822020-10-06 17:43:35 -0700685void Logger::ResetStatisics() {
686 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
687 max_message_fetch_time_channel_ = -1;
688 max_message_fetch_time_size_ = -1;
689 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
690 total_message_fetch_count_ = 0;
691 total_message_fetch_bytes_ = 0;
692 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
693 total_nop_fetch_count_ = 0;
694 max_copy_time_ = std::chrono::nanoseconds::zero();
695 max_copy_time_channel_ = -1;
696 max_copy_time_size_ = -1;
697 total_copy_time_ = std::chrono::nanoseconds::zero();
698 total_copy_count_ = 0;
699 total_copy_bytes_ = 0;
700}
701
Austin Schuh2f8fd752020-09-01 22:38:28 -0700702void Logger::Rotate() {
703 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700704 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700705 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700706 }
707}
708
709void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800710 // Grab the latest ServerStatistics message. This will always have the
711 // oppertunity to be >= to the current time, so it will always represent any
712 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700713 WriteMissingTimestamps();
714
715 // Write each channel to disk, one at a time.
716 for (FetcherStruct &f : fetchers_) {
717 while (true) {
718 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700719 const auto start = event_loop_->monotonic_now();
720 const bool got_new = f.fetcher->FetchNext();
721 const auto end = event_loop_->monotonic_now();
722 RecordFetchResult(start, end, got_new, &f);
723 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700724 VLOG(2) << "No new data on "
725 << configuration::CleanedChannelToString(
726 f.fetcher->channel());
727 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700728 }
Brian Silvermancb805822020-10-06 17:43:35 -0700729 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700730 }
731
Austin Schuh2f8fd752020-09-01 22:38:28 -0700732 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700733 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700734 break;
735 }
Brian Silvermancb805822020-10-06 17:43:35 -0700736 if (f.writer != nullptr) {
737 // Write!
738 const auto start = event_loop_->monotonic_now();
739 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
740 max_header_size_);
741 fbb.ForceDefaults(true);
742
743 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
744 f.channel_index, f.log_type));
745 const auto end = event_loop_->monotonic_now();
746 RecordCreateMessageTime(start, end, &f);
747
748 VLOG(2) << "Writing data as node "
749 << FlatbufferToJson(event_loop_->node()) << " for channel "
750 << configuration::CleanedChannelToString(f.fetcher->channel())
751 << " to " << f.writer->filename() << " data "
752 << FlatbufferToJson(
753 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
754 fbb.GetBufferPointer()));
755
756 max_header_size_ = std::max(max_header_size_,
757 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800758 CHECK(node_state_[f.data_node_index].header_valid)
759 << ": Can't write data before the header on channel "
760 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700761 f.writer->QueueSizedFlatbuffer(&fbb);
762 }
763
764 if (f.timestamp_writer != nullptr) {
765 // And now handle timestamps.
766 const auto start = event_loop_->monotonic_now();
767 flatbuffers::FlatBufferBuilder fbb;
768 fbb.ForceDefaults(true);
769
770 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
771 f.channel_index,
772 LogType::kLogDeliveryTimeOnly));
773 const auto end = event_loop_->monotonic_now();
774 RecordCreateMessageTime(start, end, &f);
775
776 VLOG(2) << "Writing timestamps as node "
777 << FlatbufferToJson(event_loop_->node()) << " for channel "
778 << configuration::CleanedChannelToString(f.fetcher->channel())
779 << " to " << f.timestamp_writer->filename() << " timestamp "
780 << FlatbufferToJson(
781 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
782 fbb.GetBufferPointer()));
783
Austin Schuh315b96b2020-12-11 21:21:12 -0800784 CHECK(node_state_[f.timestamp_node_index].header_valid)
785 << ": Can't write data before the header on channel "
786 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700787 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
788 }
789
790 if (f.contents_writer != nullptr) {
791 const auto start = event_loop_->monotonic_now();
792 // And now handle the special message contents channel. Copy the
793 // message into a FlatBufferBuilder and save it to disk.
794 // TODO(austin): We can be more efficient here when we start to
795 // care...
796 flatbuffers::FlatBufferBuilder fbb;
797 fbb.ForceDefaults(true);
798
Austin Schuh0de30f32020-12-06 12:44:28 -0800799 const RemoteMessage *msg =
800 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700801
Austin Schuh315b96b2020-12-11 21:21:12 -0800802 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
803 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
804 node_state_[f.contents_node_index].source_node_boot_uuid !=
805 msg->boot_uuid()->string_view()) {
806 node_state_[f.contents_node_index].SetBootUUID(
807 msg->boot_uuid()->string_view());
808
809 MaybeWriteHeader(f.contents_node_index);
810 }
811
Brian Silvermancb805822020-10-06 17:43:35 -0700812 logger::MessageHeader::Builder message_header_builder(fbb);
813
814 // TODO(austin): This needs to check the channel_index and confirm
815 // that it should be logged before squirreling away the timestamp to
816 // disk. We don't want to log irrelevant timestamps.
817
818 // Note: this must match the same order as MessageBridgeServer and
819 // PackMessage. We want identical headers to have identical
820 // on-the-wire formats to make comparing them easier.
821
822 // Translate from the channel index that the event loop uses to the
823 // channel index in the log file.
824 message_header_builder.add_channel_index(
825 event_loop_to_logged_channel_index_[msg->channel_index()]);
826
827 message_header_builder.add_queue_index(msg->queue_index());
828 message_header_builder.add_monotonic_sent_time(
829 msg->monotonic_sent_time());
830 message_header_builder.add_realtime_sent_time(
831 msg->realtime_sent_time());
832
833 message_header_builder.add_monotonic_remote_time(
834 msg->monotonic_remote_time());
835 message_header_builder.add_realtime_remote_time(
836 msg->realtime_remote_time());
837 message_header_builder.add_remote_queue_index(
838 msg->remote_queue_index());
839
840 fbb.FinishSizePrefixed(message_header_builder.Finish());
841 const auto end = event_loop_->monotonic_now();
842 RecordCreateMessageTime(start, end, &f);
843
Austin Schuh315b96b2020-12-11 21:21:12 -0800844 CHECK(node_state_[f.contents_node_index].header_valid)
845 << ": Can't write data before the header on channel "
846 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700847 f.contents_writer->QueueSizedFlatbuffer(&fbb);
848 }
849
850 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700851 }
852 }
853 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800854}
855
Brian Silverman1f345222020-09-24 21:14:48 -0700856void Logger::DoLogData(const monotonic_clock::time_point end_time) {
857 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800858 // max_out_of_order_duration. To do this, we need sync points. Every write
859 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800860
861 do {
862 // Move the sync point up by at most polling_period. This forces one sync
863 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700864 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
865
866 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800867
Austin Schuhe309d2a2019-11-29 13:25:21 -0800868 // If we missed cycles, we could be pretty far behind. Spin until we are
869 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700870 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800871}
872
Brian Silvermancb805822020-10-06 17:43:35 -0700873void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
874 aos::monotonic_clock::time_point end,
875 bool got_new, FetcherStruct *fetcher) {
876 const auto duration = end - start;
877 if (!got_new) {
878 ++total_nop_fetch_count_;
879 total_nop_fetch_time_ += duration;
880 return;
881 }
882 ++total_message_fetch_count_;
883 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
884 total_message_fetch_time_ += duration;
885 if (duration > max_message_fetch_time_) {
886 max_message_fetch_time_ = duration;
887 max_message_fetch_time_channel_ = fetcher->channel_index;
888 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
889 }
890}
891
892void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
893 aos::monotonic_clock::time_point end,
894 FetcherStruct *fetcher) {
895 const auto duration = end - start;
896 total_copy_time_ += duration;
897 ++total_copy_count_;
898 total_copy_bytes_ += fetcher->fetcher->context().size;
899 if (duration > max_copy_time_) {
900 max_copy_time_ = duration;
901 max_copy_time_channel_ = fetcher->channel_index;
902 max_copy_time_size_ = fetcher->fetcher->context().size;
903 }
904}
905
Austin Schuh11d43732020-09-21 17:28:30 -0700906std::vector<std::vector<std::string>> ToLogReaderVector(
907 const std::vector<LogFile> &log_files) {
908 std::vector<std::vector<std::string>> result;
909 for (const LogFile &log_file : log_files) {
910 for (const LogParts &log_parts : log_file.parts) {
911 std::vector<std::string> parts;
912 for (const std::string &part : log_parts.parts) {
913 parts.emplace_back(part);
914 }
915 result.emplace_back(std::move(parts));
916 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700917 }
918 return result;
919}
920
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800921LogReader::LogReader(std::string_view filename,
922 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800923 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800924
Austin Schuh287d43d2020-12-04 20:19:33 -0800925LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800926 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800927 : log_files_(std::move(log_files)),
928 log_file_header_(MaybeReadHeaderOrDie(log_files_)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800929 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800930 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800931
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700932 // Remap all existing remote timestamp channels. They will be recreated, and
933 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700934 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700935 std::vector<const Node *> timestamp_logger_nodes =
936 configuration::TimestampNodes(logged_configuration(), node);
937 for (const Node *remote_node : timestamp_logger_nodes) {
938 const std::string channel = absl::StrCat(
939 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800940 // See if the log file is an old log with MessageHeader channels in it, or
941 // a newer log with RemoteMessage. If we find an older log, rename the
942 // type too along with the name.
943 if (HasChannel<MessageHeader>(channel, node)) {
944 CHECK(!HasChannel<RemoteMessage>(channel, node))
945 << ": Can't have both a MessageHeader and RemoteMessage remote "
946 "timestamp channel.";
947 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
948 "aos.message_bridge.RemoteMessage");
949 } else {
950 CHECK(HasChannel<RemoteMessage>(channel, node))
951 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
952 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
953 << node->name()->string_view();
954 RemapLoggedChannel<RemoteMessage>(channel, node);
955 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700956 }
957 }
958
Austin Schuh6aa77be2020-02-22 21:06:40 -0800959 if (replay_configuration) {
960 CHECK_EQ(configuration::MultiNode(configuration()),
961 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700962 << ": Log file and replay config need to both be multi or single "
963 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800964 }
965
Austin Schuh6f3babe2020-01-26 20:34:50 -0800966 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800967 states_.emplace_back(std::make_unique<State>(
968 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800969 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800970 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700971 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800972 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700973 << ": Log file and replay config need to have matching nodes "
974 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700975 for (const Node *node : *logged_configuration()->nodes()) {
976 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700977 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
978 << " in logged config that is not present in the replay "
979 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700980 }
981 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800982 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800983 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800984 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800985}
986
Austin Schuh6aa77be2020-02-22 21:06:40 -0800987LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700988 if (event_loop_factory_unique_ptr_) {
989 Deregister();
990 } else if (event_loop_factory_ != nullptr) {
991 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
992 "is destroyed";
993 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700994 // Zero out some buffers. It's easy to do use-after-frees on these, so make
995 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700996 if (remapped_configuration_buffer_) {
997 remapped_configuration_buffer_->Wipe();
998 }
999 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -08001000}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001001
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001002const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001003 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001004}
1005
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001006const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001007 return remapped_configuration_;
1008}
1009
Austin Schuh6f3babe2020-01-26 20:34:50 -08001010std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 // Because the Node pointer will only be valid if it actually points to
1012 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001013 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001014 //
1015 // Also, note, that when ever a map is changed, the nodes in here are
1016 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001017 CHECK(remapped_configuration_ != nullptr)
1018 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001019 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001020}
Austin Schuh15649d62019-12-28 16:36:38 -08001021
Austin Schuh11d43732020-09-21 17:28:30 -07001022monotonic_clock::time_point LogReader::monotonic_start_time(
1023 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001024 State *state =
1025 states_[configuration::GetNodeIndex(configuration(), node)].get();
1026 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1027
Austin Schuh858c9f32020-08-31 16:56:12 -07001028 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001029}
1030
Austin Schuh11d43732020-09-21 17:28:30 -07001031realtime_clock::time_point LogReader::realtime_start_time(
1032 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001033 State *state =
1034 states_[configuration::GetNodeIndex(configuration(), node)].get();
1035 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1036
Austin Schuh858c9f32020-08-31 16:56:12 -07001037 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001038}
1039
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001040void LogReader::Register() {
1041 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001042 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001043 Register(event_loop_factory_unique_ptr_.get());
1044}
1045
Austin Schuh92547522019-12-28 14:33:43 -08001046void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001047 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001048 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001049 filters_ =
1050 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
1051 event_loop_factory_);
Austin Schuh92547522019-12-28 14:33:43 -08001052
Brian Silvermand90905f2020-09-23 14:42:56 -07001053 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001054 const size_t node_index =
1055 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001056 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1057 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001058
1059 // Confirm that all the parts are from the same boot if there are enough
1060 // parts to not be from the same boot.
1061 if (filtered_parts.size() > 1u) {
1062 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1063 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1064 filtered_parts[0].source_boot_uuid)
1065 << ": Found parts from different boots "
1066 << LogFileVectorToString(log_files_);
1067 }
1068 }
1069
Austin Schuh287d43d2020-12-04 20:19:33 -08001070 states_[node_index] = std::make_unique<State>(
1071 filtered_parts.size() == 0u
1072 ? nullptr
1073 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001074 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001075 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001076 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001077
1078 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001079 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001080
Austin Schuh287d43d2020-12-04 20:19:33 -08001081 for (const Node *node : configuration::GetNodes(configuration())) {
1082 const size_t node_index =
1083 configuration::GetNodeIndex(configuration(), node);
1084 State *state = states_[node_index].get();
1085 for (const Node *other_node : configuration::GetNodes(configuration())) {
1086 const size_t other_node_index =
1087 configuration::GetNodeIndex(configuration(), other_node);
1088 State *other_state = states_[other_node_index].get();
1089 if (other_state != state) {
1090 state->AddPeer(other_state);
1091 }
1092 }
1093 }
1094
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001095 // Register after making all the State objects so we can build references
1096 // between them.
1097 for (const Node *node : configuration::GetNodes(configuration())) {
1098 const size_t node_index =
1099 configuration::GetNodeIndex(configuration(), node);
1100 State *state = states_[node_index].get();
1101
1102 Register(state->event_loop());
1103 }
1104
James Kuszmaul46d82582020-05-09 19:50:09 -07001105 if (live_nodes_ == 0) {
1106 LOG(FATAL)
1107 << "Don't have logs from any of the nodes in the replay config--are "
1108 "you sure that the replay config matches the original config?";
1109 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001110
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001111 filters_->Initialize(logged_configuration());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001112
Austin Schuh858c9f32020-08-31 16:56:12 -07001113 for (std::unique_ptr<State> &state : states_) {
1114 state->SeedSortedMessages();
1115 }
1116
Austin Schuh2f8fd752020-09-01 22:38:28 -07001117 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001118 UpdateOffsets();
1119
Austin Schuh2f8fd752020-09-01 22:38:28 -07001120 // We want to start the log file at the last start time of the log files
1121 // from all the nodes. Compute how long each node's simulation needs to run
1122 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001123 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001124
Austin Schuh2f8fd752020-09-01 22:38:28 -07001125 // TODO(austin): We want an "OnStart" callback for each node rather than
1126 // running until the last node.
1127
Austin Schuh8bd96322020-02-13 21:18:22 -08001128 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001129 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1130 << MaybeNodeName(state->event_loop()->node()) << "now "
1131 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001132 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1133 continue;
1134 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001135 // And start computing the start time on the distributed clock now that
1136 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001137 start_time = std::max(
1138 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001139 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001140
1141 CHECK_GE(start_time, distributed_clock::epoch())
1142 << ": Hmm, we have a node starting before the start of time. Offset "
1143 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001144
Austin Schuh6f3babe2020-01-26 20:34:50 -08001145 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1146 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001147 // nodes, and also replayed on the other nodes. This may not satisfy all
1148 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001149 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1150 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1151 const Channel *channel = logged_configuration()->channels()->Get(i);
1152 const Node *node = configuration::GetNode(
1153 configuration(), channel->source_node()->string_view());
1154
Austin Schuh8bd96322020-02-13 21:18:22 -08001155 State *state =
1156 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001157
1158 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001159 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001160
1161 event_loop_factory_->DisableForwarding(remapped_channel);
1162 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001163
1164 // If we are replaying a log, we don't want a bunch of redundant messages
1165 // from both the real message bridge and simulated message bridge.
1166 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001167 }
1168
Austin Schuhcde938c2020-02-02 17:30:07 -08001169 // While we are starting the system up, we might be relying on matching data
1170 // to timestamps on log files where the timestamp log file starts before the
1171 // data. In this case, it is reasonable to expect missing data.
1172 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001173 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001174 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001175 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001176 // Now that we are running for real, missing data means that the log file is
1177 // corrupted or went wrong.
1178 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001179
Austin Schuh8bd96322020-02-13 21:18:22 -08001180 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001181 // Make the RT clock be correct before handing it to the user.
1182 if (state->realtime_start_time() != realtime_clock::min_time) {
1183 state->SetRealtimeOffset(state->monotonic_start_time(),
1184 state->realtime_start_time());
1185 }
1186 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1187 << MaybeNodeName(state->event_loop()->node()) << "now "
1188 << state->monotonic_now();
1189 }
1190
1191 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001192 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -08001193 }
1194}
1195
Austin Schuh2f8fd752020-09-01 22:38:28 -07001196void LogReader::UpdateOffsets() {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001197 filters_->UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001198
1199 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001200 filters_->LogFit("Offset is");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001201 }
1202}
1203
1204message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001205 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001206 if (filters_) {
1207 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001208 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001209 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001210}
1211
Austin Schuhe309d2a2019-11-29 13:25:21 -08001212void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001213 State *state =
1214 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1215 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001216
Austin Schuh858c9f32020-08-31 16:56:12 -07001217 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001218
Tyler Chatow67ddb032020-01-12 14:30:04 -08001219 // We don't run timing reports when trying to print out logged data, because
1220 // otherwise we would end up printing out the timing reports themselves...
1221 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001222 event_loop->SkipTimingReport();
1223 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001224
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001225 for (size_t logged_channel_index = 0;
1226 logged_channel_index < logged_configuration()->channels()->size();
1227 ++logged_channel_index) {
1228 const Channel *channel = RemapChannel(
1229 event_loop,
1230 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001231
Austin Schuh2f8fd752020-09-01 22:38:28 -07001232 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001233 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001234
1235 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001236
1237 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1238 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001239 // We've got a message which is being forwarded to this node.
1240 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001241 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001242 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001243
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001244 // Delivery timestamps are supposed to be logged back on the source node.
1245 // Configure remote timestamps to be sent.
1246 const bool delivery_time_is_logged =
1247 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1248 channel, event_loop->node(), source_node);
1249
1250 source_state =
1251 states_[configuration::GetNodeIndex(configuration(), source_node)]
1252 .get();
1253
1254 if (delivery_time_is_logged) {
1255 remote_timestamp_sender =
1256 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001257 }
1258 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001259
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001260 state->SetChannel(
1261 logged_channel_index,
1262 configuration::ChannelIndex(event_loop->configuration(), channel),
1263 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1264 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001265 }
1266
Austin Schuh6aa77be2020-02-22 21:06:40 -08001267 // If we didn't find any log files with data in them, we won't ever get a
1268 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001269 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001270 return;
1271 }
1272
Austin Schuh858c9f32020-08-31 16:56:12 -07001273 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001274 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1275 << "at " << state->event_loop()->context().monotonic_event_time
1276 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001277 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001278 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001279 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001280 if (live_nodes_ == 0) {
1281 event_loop_factory_->Exit();
1282 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001283 return;
1284 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001285 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001286 filters_->LogFit("Offset was");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001287 }
1288
1289 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001290 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001291
Austin Schuhe309d2a2019-11-29 13:25:21 -08001292 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001293 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001294 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001295 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001296 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1297 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001298 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001299 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001300 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001301 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001302 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001303 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001304 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001305 << "): " << FlatbufferToJson(state->event_loop()->node())
1306 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001307 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001308 << state->DebugString();
1309 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001310
Austin Schuh287d43d2020-12-04 20:19:33 -08001311 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001312 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001313 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001314 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001315 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001316 timestamped_message.data.span().size() != 0u) {
1317 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001318 << ": Got a message without data on channel "
1319 << configuration::CleanedChannelToString(
1320 logged_configuration()->channels()->Get(
1321 timestamped_message.channel_index))
1322 << ". Forwarding entry which was not matched? Use "
1323 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001324
Austin Schuh2f8fd752020-09-01 22:38:28 -07001325 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001326 // Confirm that the message was sent on the sending node before the
1327 // destination node (this node). As a proxy, do this by making sure
1328 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001329 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001330 CHECK_LT(
1331 timestamped_message.monotonic_remote_time,
1332 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001333 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001334 << state->remote_node(timestamped_message.channel_index)
1335 ->name()
1336 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001337 << " while trying to send a message on "
1338 << configuration::CleanedChannelToString(
1339 logged_configuration()->channels()->Get(
1340 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001341 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001342 } else if (timestamped_message.monotonic_remote_time >=
1343 state->monotonic_remote_now(
1344 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001345 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001346 << "Check failed: timestamped_message.monotonic_remote_time < "
1347 "state->monotonic_remote_now(timestamped_message.channel_"
1348 "index) ("
1349 << timestamped_message.monotonic_remote_time << " vs. "
1350 << state->monotonic_remote_now(
1351 timestamped_message.channel_index)
1352 << ") " << state->event_loop()->node()->name()->string_view()
1353 << " to "
1354 << state->remote_node(timestamped_message.channel_index)
1355 ->name()
1356 ->string_view()
1357 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001358 << " ("
1359 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001360 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001362 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001363 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 timestamped_message.channel_index,
1365 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001366 << ") " << state->DebugString();
1367 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001368 }
1369
Austin Schuh15649d62019-12-28 16:36:38 -08001370 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001371 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1372 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001373
Austin Schuh2f8fd752020-09-01 22:38:28 -07001374 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001375 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001376 // TODO(austin): std::move channel_data in and make that efficient in
1377 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001378 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001379 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001380 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001381 // reading the rest of the log file and call it quits. We don't want
1382 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001383 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1384 bool update_time_dummy;
1385 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001386 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001387 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001388 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001389 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001390 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001391 LOG(WARNING)
1392 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001393 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001394 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001395 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001396 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001397 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001398 }
1399
Austin Schuh858c9f32020-08-31 16:56:12 -07001400 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001401 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001402 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1403 << "wakeup for " << next_time << "("
1404 << state->ToDistributedClock(next_time)
1405 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001406 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001407 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001408 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1409 << "No next message, scheduling shutdown";
1410 // Set a timer up immediately after now to die. If we don't do this,
1411 // then the senders waiting on the message we just read will never get
1412 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001413 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001414 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1415 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001416 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001417 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001418
Austin Schuh2f8fd752020-09-01 22:38:28 -07001419 // Once we make this call, the current time changes. So do everything
1420 // which involves time before changing it. That especially includes
1421 // sending the message.
1422 if (update_time) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001423 filters_->LogFit("");
1424
Austin Schuh2f8fd752020-09-01 22:38:28 -07001425 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1426 << "updating offsets";
1427
1428 std::vector<aos::monotonic_clock::time_point> before_times;
1429 before_times.resize(states_.size());
1430 std::transform(states_.begin(), states_.end(), before_times.begin(),
1431 [](const std::unique_ptr<State> &state) {
1432 return state->monotonic_now();
1433 });
1434
1435 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001436 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1437 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001438 }
1439
Austin Schuh8bd96322020-02-13 21:18:22 -08001440 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001441 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1442 << state->monotonic_now();
1443
1444 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001445 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1446 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001447 }
1448
1449 // TODO(austin): We should be perfect.
1450 const std::chrono::nanoseconds kTolerance{3};
1451 if (!FLAGS_skip_order_validation) {
1452 CHECK_GE(next_time, state->monotonic_now())
1453 << ": Time skipped the next event.";
1454
1455 for (size_t i = 0; i < states_.size(); ++i) {
1456 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1457 << ": Time changed too much on node "
1458 << MaybeNodeName(states_[i]->event_loop()->node());
1459 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1460 << ": Time changed too much on node "
1461 << states_[i]->event_loop()->node()->name()->string_view();
1462 }
1463 } else {
1464 if (next_time < state->monotonic_now()) {
1465 LOG(WARNING) << "Check failed: next_time >= "
1466 "state->monotonic_now() ("
1467 << next_time << " vs. " << state->monotonic_now()
1468 << "): Time skipped the next event.";
1469 }
1470 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001471 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001472 LOG(WARNING) << "Check failed: "
1473 "states_[i]->monotonic_now() "
1474 ">= before_times[i] - kTolerance ("
1475 << states_[i]->monotonic_now() << " vs. "
1476 << before_times[i] - kTolerance
1477 << ") : Time changed too much on node "
1478 << MaybeNodeName(states_[i]->event_loop()->node());
1479 }
Austin Schuh724032b2020-12-18 22:54:59 -08001480 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001481 LOG(WARNING) << "Check failed: "
1482 "states_[i]->monotonic_now() "
1483 "<= before_times[i] + kTolerance ("
1484 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001485 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001486 << ") : Time changed too much on node "
1487 << MaybeNodeName(states_[i]->event_loop()->node());
1488 }
1489 }
1490 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001491 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001492
1493 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1494 << state->event_loop()->context().monotonic_event_time << " now "
1495 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001496 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001497
Austin Schuh6f3babe2020-01-26 20:34:50 -08001498 ++live_nodes_;
1499
Austin Schuh858c9f32020-08-31 16:56:12 -07001500 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1501 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001502 }
1503}
1504
1505void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001506 // Make sure that things get destroyed in the correct order, rather than
1507 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001508 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001509 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001510 }
Austin Schuh92547522019-12-28 14:33:43 -08001511
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001512 event_loop_factory_unique_ptr_.reset();
1513 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001514}
1515
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001516void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001517 std::string_view add_prefix,
1518 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001519 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1520 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1521 if (channel->name()->str() == name &&
1522 channel->type()->string_view() == type) {
1523 CHECK_EQ(0u, remapped_channels_.count(ii))
1524 << "Already remapped channel "
1525 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001526 RemappedChannel remapped_channel;
1527 remapped_channel.remapped_name =
1528 std::string(add_prefix) + std::string(name);
1529 remapped_channel.new_type = new_type;
1530 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001531 VLOG(1) << "Remapping channel "
1532 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001533 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001534 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001535 return;
1536 }
1537 }
1538 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1539 << type;
1540}
1541
Austin Schuh01b4c352020-09-21 23:09:39 -07001542void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1543 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001544 std::string_view add_prefix,
1545 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001546 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1547 const Channel *remapped_channel =
1548 configuration::GetChannel(logged_configuration(), name, type, "", node);
1549 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1550 << "\", \"type\": \"" << type << "\"}";
1551 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1552 << "\"}";
1553 VLOG(1) << "Remapped "
1554 << aos::configuration::StrippedChannelToString(remapped_channel);
1555
1556 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1557 // we want it to degrade if the heuristics fail to just work.
1558 //
1559 // The easiest way to do this is going to be incredibly specific and verbose.
1560 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1561 // /original/0/spray. Then, create a map from /original/spray to
1562 // /original/0/spray for just the type we were asked for.
1563 if (name != remapped_channel->name()->string_view()) {
1564 MapT new_map;
1565 new_map.match = std::make_unique<ChannelT>();
1566 new_map.match->name = absl::StrCat(add_prefix, name);
1567 new_map.match->type = type;
1568 if (node != nullptr) {
1569 new_map.match->source_node = node->name()->str();
1570 }
1571 new_map.rename = std::make_unique<ChannelT>();
1572 new_map.rename->name =
1573 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1574 maps_.emplace_back(std::move(new_map));
1575 }
1576
1577 const size_t channel_index =
1578 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1579 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1580 << "Already remapped channel "
1581 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001582
1583 RemappedChannel remapped_channel_struct;
1584 remapped_channel_struct.remapped_name =
1585 std::string(add_prefix) +
1586 std::string(remapped_channel->name()->string_view());
1587 remapped_channel_struct.new_type = new_type;
1588 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001589 MakeRemappedConfig();
1590}
1591
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001592void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001593 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001594 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001595 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001596 << ": Can't change the mapping after the events are scheduled.";
1597 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001598 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001599
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001600 // If no remapping occurred and we are using the original config, then there
1601 // is nothing interesting to do here.
1602 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001603 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001604 return;
1605 }
1606 // Config to copy Channel definitions from. Use the specified
1607 // replay_configuration_ if it has been provided.
1608 const Configuration *const base_config = replay_configuration_ == nullptr
1609 ? logged_configuration()
1610 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001611
1612 // Create a config with all the channels, but un-sorted/merged. Collect up
1613 // the schemas while we do this. Call MergeConfiguration to sort everything,
1614 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001615
1616 // This is the builder that we use for the config containing all the new
1617 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001618 flatbuffers::FlatBufferBuilder fbb;
1619 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001620 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001621
1622 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1623 << ": Merging logic needs to be updated when the number of channel "
1624 "fields changes.";
1625
1626 // List of schemas.
1627 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1628 // Make sure our new RemoteMessage schema is in there for old logs without it.
1629 schema_map.insert(std::make_pair(
1630 RemoteMessage::GetFullyQualifiedName(),
1631 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1632 message_bridge::RemoteMessageSchema()))));
1633
1634 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001635 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001636 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001637 base_config, logged_configuration()->channels()->Get(pair.first), "",
1638 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001639 channel_offsets.emplace_back(
1640 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001641 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001642
Austin Schuh0de30f32020-12-06 12:44:28 -08001643 // Now reconstruct the original channels, translating types as needed
1644 for (const Channel *c : *base_config->channels()) {
1645 // Search for a mapping channel.
1646 std::string_view new_type = "";
1647 for (auto &pair : remapped_channels_) {
1648 const Channel *const remapped_channel =
1649 logged_configuration()->channels()->Get(pair.first);
1650 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1651 remapped_channel->type()->string_view() == c->type()->string_view()) {
1652 new_type = pair.second.new_type;
1653 break;
1654 }
1655 }
1656
1657 // Copy everything over.
1658 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1659
1660 // Add the schema if it doesn't exist.
1661 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1662 CHECK(c->has_schema());
1663 schema_map.insert(std::make_pair(c->type()->string_view(),
1664 RecursiveCopyFlatBuffer(c->schema())));
1665 }
1666 }
1667
1668 // The MergeConfiguration API takes a vector, not a map. Convert.
1669 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1670 while (!schema_map.empty()) {
1671 schemas.emplace_back(std::move(schema_map.begin()->second));
1672 schema_map.erase(schema_map.begin());
1673 }
1674
1675 // Create the Configuration containing the new channels that we want to add.
1676 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1677 channels_offset =
1678 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1679
1680 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001681 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001682 if (base_config->maps()) {
1683 for (const Map *map : *base_config->maps()) {
1684 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1685 }
1686 }
1687
1688 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001689 for (const MapT &map : maps_) {
1690 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001691 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001692 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001693 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001694 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001695 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001696 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1697 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001698 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001699 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001700 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001701 match_builder.add_name(match_name_offset);
1702 match_builder.add_type(match_type_offset);
1703 if (!map.match->source_node.empty()) {
1704 match_builder.add_source_node(match_source_node_offset);
1705 }
1706 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1707
Austin Schuh0de30f32020-12-06 12:44:28 -08001708 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001709 rename_builder.add_name(rename_name_offset);
1710 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1711
Austin Schuh0de30f32020-12-06 12:44:28 -08001712 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001713 map_builder.add_match(match_offset);
1714 map_builder.add_rename(rename_offset);
1715 map_offsets.emplace_back(map_builder.Finish());
1716 }
1717
Austin Schuh0de30f32020-12-06 12:44:28 -08001718 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1719 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001720
Austin Schuh0de30f32020-12-06 12:44:28 -08001721 // And copy everything else over.
1722 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1723 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1724
1725 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1726 applications_offset =
1727 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1728
1729 // Now insert everything else in unmodified.
1730 ConfigurationBuilder configuration_builder(fbb);
1731 if (!channels_offset.IsNull()) {
1732 configuration_builder.add_channels(channels_offset);
1733 }
1734 if (!maps_offsets.IsNull()) {
1735 configuration_builder.add_maps(maps_offsets);
1736 }
1737 if (!nodes_offset.IsNull()) {
1738 configuration_builder.add_nodes(nodes_offset);
1739 }
1740 if (!applications_offset.IsNull()) {
1741 configuration_builder.add_applications(applications_offset);
1742 }
1743
1744 if (base_config->has_channel_storage_duration()) {
1745 configuration_builder.add_channel_storage_duration(
1746 base_config->channel_storage_duration());
1747 }
1748
1749 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1750 << ": Merging logic needs to be updated when the number of configuration "
1751 "fields changes.";
1752
1753 fbb.Finish(configuration_builder.Finish());
1754
1755 // Clean it up and return it! By using MergeConfiguration here, we'll
1756 // actually get a deduplicated config for free too.
1757 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1758 configuration::MergeConfiguration(
1759 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1760
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001761 remapped_configuration_buffer_ =
1762 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001763 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001764
1765 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001766
1767 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001768}
1769
Austin Schuh6f3babe2020-01-26 20:34:50 -08001770const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1771 const Channel *channel) {
1772 std::string_view channel_name = channel->name()->string_view();
1773 std::string_view channel_type = channel->type()->string_view();
1774 const int channel_index =
1775 configuration::ChannelIndex(logged_configuration(), channel);
1776 // If the channel is remapped, find the correct channel name to use.
1777 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001778 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001779 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001780 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001781 }
1782
Austin Schuhee711052020-08-24 16:06:09 -07001783 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001784 const Channel *remapped_channel = configuration::GetChannel(
1785 event_loop->configuration(), channel_name, channel_type,
1786 event_loop->name(), event_loop->node());
1787
1788 CHECK(remapped_channel != nullptr)
1789 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1790 << channel_type << "\"} because it is not in the provided configuration.";
1791
1792 return remapped_channel;
1793}
1794
Austin Schuh287d43d2020-12-04 20:19:33 -08001795LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1796 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1797
1798void LogReader::State::AddPeer(State *peer) {
1799 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1800 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1801 }
1802}
Austin Schuh858c9f32020-08-31 16:56:12 -07001803
1804EventLoop *LogReader::State::SetNodeEventLoopFactory(
1805 NodeEventLoopFactory *node_event_loop_factory) {
1806 node_event_loop_factory_ = node_event_loop_factory;
1807 event_loop_unique_ptr_ =
1808 node_event_loop_factory_->MakeEventLoop("log_reader");
1809 return event_loop_unique_ptr_.get();
1810}
1811
1812void LogReader::State::SetChannelCount(size_t count) {
1813 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001814 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001815 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001816 channel_source_state_.resize(count);
1817 factory_channel_index_.resize(count);
1818 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001819}
1820
1821void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001822 size_t logged_channel_index, size_t factory_channel_index,
1823 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001824 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08001825 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001826 channels_[logged_channel_index] = std::move(sender);
1827 filters_[logged_channel_index] = filter;
1828 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1829
1830 if (source_state) {
1831 channel_source_state_[logged_channel_index] = source_state;
1832
1833 if (remote_timestamp_sender != nullptr) {
1834 source_state->queue_index_map_[logged_channel_index] =
1835 std::make_unique<std::vector<State::SentTimestamp>>();
1836 }
1837 }
1838
1839 factory_channel_index_[logged_channel_index] = factory_channel_index;
1840}
1841
Austin Schuh287d43d2020-12-04 20:19:33 -08001842bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1843 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001844 uint32_t remote_queue_index = 0xffffffff;
1845
Austin Schuh287d43d2020-12-04 20:19:33 -08001846 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
1847 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
1848 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1849 ->queue_index_map_[timestamped_message.channel_index]
1850 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001851
1852 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08001853 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
1854 search.realtime_event_time = timestamped_message.realtime_remote_time;
1855 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001856
1857 // Find the sent time if available.
1858 auto element = std::lower_bound(
1859 queue_index_map->begin(), queue_index_map->end(), search,
1860 [](SentTimestamp a, SentTimestamp b) {
1861 if (b.monotonic_event_time < a.monotonic_event_time) {
1862 return false;
1863 }
1864 if (b.monotonic_event_time > a.monotonic_event_time) {
1865 return true;
1866 }
1867
1868 if (b.queue_index < a.queue_index) {
1869 return false;
1870 }
1871 if (b.queue_index > a.queue_index) {
1872 return true;
1873 }
1874
1875 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1876 return false;
1877 });
1878
1879 // TODO(austin): Be a bit more principled here, but we will want to do that
1880 // after the logger rewrite. We hit this when one node finishes, but the
1881 // other node isn't done yet. So there is no send time, but there is a
1882 // receive time.
1883 if (element != queue_index_map->end()) {
1884 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001885 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001886 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001887 timestamped_message.realtime_remote_time);
1888 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001889
1890 remote_queue_index = element->actual_queue_index;
1891 }
1892 }
1893
1894 // Send! Use the replayed queue index here instead of the logged queue index
1895 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001896 const bool sent = sender->Send(
1897 timestamped_message.data.message().data()->Data(),
1898 timestamped_message.data.message().data()->size(),
1899 timestamped_message.monotonic_remote_time,
1900 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001901 if (!sent) return false;
1902
Austin Schuh287d43d2020-12-04 20:19:33 -08001903 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001904 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08001905 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
1906 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
1907 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001908 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08001909 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1910 timestamp);
1911 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1912 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001913 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08001914 remote_timestamp_senders_[timestamped_message.channel_index]
1915 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001916
Austin Schuh315b96b2020-12-11 21:21:12 -08001917 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
1918 builder.fbb()->CreateString(event_loop_->boot_uuid().string_view());
1919
Austin Schuh0de30f32020-12-06 12:44:28 -08001920 RemoteMessage::Builder message_header_builder =
1921 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001922
1923 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001924 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001925
1926 // Swap the remote and sent metrics. They are from the sender's
1927 // perspective, not the receiver's perspective.
1928 message_header_builder.add_monotonic_sent_time(
1929 sender->monotonic_sent_time().time_since_epoch().count());
1930 message_header_builder.add_realtime_sent_time(
1931 sender->realtime_sent_time().time_since_epoch().count());
1932 message_header_builder.add_queue_index(sender->sent_queue_index());
1933
1934 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001935 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001936 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001937 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001938
1939 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001940 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001941
1942 builder.Send(message_header_builder.Finish());
1943 }
1944
1945 return true;
1946}
1947
Austin Schuh0de30f32020-12-06 12:44:28 -08001948aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001949 const Node *delivered_node) {
1950 auto sender = remote_timestamp_senders_map_.find(delivered_node);
1951
1952 if (sender == remote_timestamp_senders_map_.end()) {
1953 sender = remote_timestamp_senders_map_
1954 .emplace(std::make_pair(
1955 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001956 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001957 absl::StrCat("/aos/remote_timestamps/",
1958 delivered_node->name()->string_view()))))
1959 .first;
1960 }
1961
1962 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07001963}
1964
Austin Schuh287d43d2020-12-04 20:19:33 -08001965TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001966 CHECK_GT(sorted_messages_.size(), 0u);
1967
Austin Schuh287d43d2020-12-04 20:19:33 -08001968 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001969 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001970 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001971 << std::get<0>(result).monotonic_event_time;
1972 sorted_messages_.pop_front();
1973 SeedSortedMessages();
1974
Austin Schuh287d43d2020-12-04 20:19:33 -08001975 if (std::get<1>(result) != nullptr) {
1976 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07001977 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1978 } else {
1979 *update_time = false;
1980 }
Austin Schuh287d43d2020-12-04 20:19:33 -08001981 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07001982}
1983
1984monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1985 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001986 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001987 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1988 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1989 }
1990
Austin Schuh287d43d2020-12-04 20:19:33 -08001991 TimestampedMessage *m =
1992 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
1993 if (m == nullptr) {
1994 return monotonic_clock::max_time;
1995 }
1996 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001997}
1998
1999void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002000 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002001 const aos::monotonic_clock::time_point end_queue_time =
2002 (sorted_messages_.size() > 0
2003 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002004 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuh858c9f32020-08-31 16:56:12 -07002005 std::chrono::seconds(2);
2006
2007 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002008 TimestampedMessage *m = timestamp_mapper_->Front();
2009 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002010 return;
2011 }
2012 if (sorted_messages_.size() > 0) {
2013 // Stop placing sorted messages on the list once we have 2 seconds
2014 // queued up (but queue at least until the log starts.
2015 if (end_queue_time <
2016 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2017 return;
2018 }
2019 }
2020
Austin Schuh2f8fd752020-09-01 22:38:28 -07002021 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2022
Austin Schuh287d43d2020-12-04 20:19:33 -08002023 TimestampedMessage timestamped_message = std::move(*m);
2024 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002025
Austin Schuh2f8fd752020-09-01 22:38:28 -07002026 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002027 if (timestamped_message.monotonic_remote_time !=
2028 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002029 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002030 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002031
2032 CHECK(filter != nullptr);
2033
2034 // Call the correct method depending on if we are the forward or
2035 // reverse direction here.
2036 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002037 timestamped_message.monotonic_event_time,
2038 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002039 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002040 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002041 }
2042}
2043
2044void LogReader::State::Deregister() {
2045 for (size_t i = 0; i < channels_.size(); ++i) {
2046 channels_[i].reset();
2047 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002048 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002049 event_loop_unique_ptr_.reset();
2050 event_loop_ = nullptr;
2051 timer_handler_ = nullptr;
2052 node_event_loop_factory_ = nullptr;
2053}
2054
Austin Schuhe309d2a2019-11-29 13:25:21 -08002055} // namespace logger
2056} // namespace aos