blob: b16ea6fe23712a862cd8809d555cfc9b4a3f88c8 [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 Schuhf0688662020-12-19 15:37:45 -080036DEFINE_double(
37 time_estimation_buffer_seconds, 2.0,
38 "The time to buffer ahead in the log file to accurately reconstruct time.");
39
Austin Schuhe309d2a2019-11-29 13:25:21 -080040namespace aos {
41namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070042namespace {
43// Helper to safely read a header, or CHECK.
Austin Schuhadd6eb32020-11-09 21:24:26 -080044SizePrefixedFlatbufferVector<LogFileHeader> MaybeReadHeaderOrDie(
Austin Schuh287d43d2020-12-04 20:19:33 -080045 const std::vector<LogFile> &log_files) {
46 CHECK_GE(log_files.size(), 1u) << ": Empty filenames list";
47 CHECK_GE(log_files[0].parts.size(), 1u) << ": Empty filenames list";
48 CHECK_GE(log_files[0].parts[0].parts.size(), 1u) << ": Empty filenames list";
Austin Schuhadd6eb32020-11-09 21:24:26 -080049 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> result =
Austin Schuh287d43d2020-12-04 20:19:33 -080050 ReadHeader(log_files[0].parts[0].parts[0]);
Austin Schuh3bd4c402020-11-06 18:19:06 -080051 CHECK(result);
52 return result.value();
Austin Schuh0afc4d12020-10-19 11:42:04 -070053}
Austin Schuh0de30f32020-12-06 12:44:28 -080054
Austin Schuh315b96b2020-12-11 21:21:12 -080055std::string LogFileVectorToString(std::vector<LogFile> log_files) {
56 std::stringstream ss;
57 for (const auto f : log_files) {
58 ss << f << "\n";
59 }
60 return ss.str();
61}
62
Austin Schuh0de30f32020-12-06 12:44:28 -080063// Copies the channel, removing the schema as we go. If new_name is provided,
64// it is used instead of the name inside the channel. If new_type is provided,
65// it is used instead of the type in the channel.
66flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
67 std::string_view new_name,
68 std::string_view new_type,
69 flatbuffers::FlatBufferBuilder *fbb) {
70 flatbuffers::Offset<flatbuffers::String> name_offset =
71 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
72 : new_name);
73 flatbuffers::Offset<flatbuffers::String> type_offset =
74 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
75 flatbuffers::Offset<flatbuffers::String> source_node_offset =
76 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
77 : 0;
78
79 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
80 destination_nodes_offset =
81 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
82
83 flatbuffers::Offset<
84 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
85 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
86
87 Channel::Builder channel_builder(*fbb);
88 channel_builder.add_name(name_offset);
89 channel_builder.add_type(type_offset);
90 if (c->has_frequency()) {
91 channel_builder.add_frequency(c->frequency());
92 }
93 if (c->has_max_size()) {
94 channel_builder.add_max_size(c->max_size());
95 }
96 if (c->has_num_senders()) {
97 channel_builder.add_num_senders(c->num_senders());
98 }
99 if (c->has_num_watchers()) {
100 channel_builder.add_num_watchers(c->num_watchers());
101 }
102 if (!source_node_offset.IsNull()) {
103 channel_builder.add_source_node(source_node_offset);
104 }
105 if (!destination_nodes_offset.IsNull()) {
106 channel_builder.add_destination_nodes(destination_nodes_offset);
107 }
108 if (c->has_logger()) {
109 channel_builder.add_logger(c->logger());
110 }
111 if (!logger_nodes_offset.IsNull()) {
112 channel_builder.add_logger_nodes(logger_nodes_offset);
113 }
114 if (c->has_read_method()) {
115 channel_builder.add_read_method(c->read_method());
116 }
117 if (c->has_num_readers()) {
118 channel_builder.add_num_readers(c->num_readers());
119 }
120 return channel_builder.Finish();
121}
122
Austin Schuhe309d2a2019-11-29 13:25:21 -0800123namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800124using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700125} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800126
Brian Silverman1f345222020-09-24 21:14:48 -0700127Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
128 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800129 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700130 configuration_(configuration),
131 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700132 timer_handler_(event_loop_->AddTimer(
133 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700134 server_statistics_fetcher_(
135 configuration::MultiNode(event_loop_->configuration())
136 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
137 "/aos")
138 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700139 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700140
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700141 // Find all the nodes which are logging timestamps on our node. This may
142 // over-estimate if should_log is specified.
143 std::vector<const Node *> timestamp_logger_nodes =
144 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700145
146 std::map<const Channel *, const Node *> timestamp_logger_channels;
147
148 // Now that we have all the nodes accumulated, make remote timestamp loggers
149 // for them.
150 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700151 // Note: since we are doing a find using the event loop channel, we need to
152 // make sure this channel pointer is part of the event loop configuration,
153 // not configuration_. This only matters when configuration_ !=
154 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700155 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700156 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800158 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 event_loop_->node());
160
161 CHECK(channel != nullptr)
162 << ": Remote timestamps are logged on "
163 << event_loop_->node()->name()->string_view()
164 << " but can't find channel /aos/remote_timestamps/"
165 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700166 if (!should_log(channel)) {
167 continue;
168 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700169 timestamp_logger_channels.insert(std::make_pair(channel, node));
170 }
171
Brian Silvermand90905f2020-09-23 14:42:56 -0700172 const size_t our_node_index =
173 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700174
Brian Silverman1f345222020-09-24 21:14:48 -0700175 for (size_t channel_index = 0;
176 channel_index < configuration_->channels()->size(); ++channel_index) {
177 const Channel *const config_channel =
178 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700179 // The MakeRawFetcher method needs a channel which is in the event loop
180 // configuration() object, not the configuration_ object. Go look that up
181 // from the config.
182 const Channel *channel = aos::configuration::GetChannel(
183 event_loop_->configuration(), config_channel->name()->string_view(),
184 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700185 CHECK(channel != nullptr)
186 << ": Failed to look up channel "
187 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700188 if (!should_log(channel)) {
189 continue;
190 }
Austin Schuh0c297012020-09-16 18:41:59 -0700191
Austin Schuhe309d2a2019-11-29 13:25:21 -0800192 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700193 fs.channel_index = channel_index;
194 fs.channel = channel;
195
Austin Schuh6f3babe2020-01-26 20:34:50 -0800196 const bool is_local =
197 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
198
Austin Schuh15649d62019-12-28 16:36:38 -0800199 const bool is_readable =
200 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700201 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
202 channel, event_loop_->node());
203 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800204
Brian Silverman1f345222020-09-24 21:14:48 -0700205 bool log_delivery_times = false;
206 if (event_loop_->node() != nullptr) {
207 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
208 channel, event_loop_->node(), event_loop_->node());
209 }
Austin Schuh15649d62019-12-28 16:36:38 -0800210
Austin Schuh0de30f32020-12-06 12:44:28 -0800211 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700212 // contents to a file directly.
213 const bool log_contents = timestamp_logger_channels.find(channel) !=
214 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700215
216 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800217 fs.fetcher = event_loop->MakeRawFetcher(channel);
218 VLOG(1) << "Logging channel "
219 << configuration::CleanedChannelToString(channel);
220
221 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800222 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700223 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800224 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800225 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800226 if (log_message) {
227 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700228 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800229 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800230 const Node *source_node = configuration::GetNode(
231 configuration_, channel->source_node()->string_view());
232 fs.data_node_index =
233 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800234 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800235 } else {
236 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800237 }
238 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700239 if (log_contents) {
240 VLOG(1) << "Timestamp logger channel "
241 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700242 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
243 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800244 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700245 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700246 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800247 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800248 }
Brian Silverman1f345222020-09-24 21:14:48 -0700249 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700250
251 // When we are logging remote timestamps, we need to be able to translate from
252 // the channel index that the event loop uses to the channel index in the
253 // config in the log file.
254 event_loop_to_logged_channel_index_.resize(
255 event_loop->configuration()->channels()->size(), -1);
256 for (size_t event_loop_channel_index = 0;
257 event_loop_channel_index <
258 event_loop->configuration()->channels()->size();
259 ++event_loop_channel_index) {
260 const Channel *event_loop_channel =
261 event_loop->configuration()->channels()->Get(event_loop_channel_index);
262
263 const Channel *logged_channel = aos::configuration::GetChannel(
264 configuration_, event_loop_channel->name()->string_view(),
265 event_loop_channel->type()->string_view(), "",
266 configuration::GetNode(configuration_, event_loop_->node()));
267
268 if (logged_channel != nullptr) {
269 event_loop_to_logged_channel_index_[event_loop_channel_index] =
270 configuration::ChannelIndex(configuration_, logged_channel);
271 }
272 }
Brian Silverman1f345222020-09-24 21:14:48 -0700273}
274
275Logger::~Logger() {
276 if (log_namer_) {
277 // If we are replaying a log file, or in simulation, we want to force the
278 // last bit of data to be logged. The easiest way to deal with this is to
279 // poll everything as we go to destroy the class, ie, shut down the logger,
280 // and write it to disk.
281 StopLogging(event_loop_->monotonic_now());
282 }
283}
284
Brian Silvermanae7c0332020-09-30 16:58:23 -0700285void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
286 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700287 CHECK(!log_namer_) << ": Already logging";
288 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700289 log_event_uuid_ = UUID::Random();
290 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700291 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
292
293 // We want to do as much work as possible before the initial Fetch. Time
294 // between that and actually starting to log opens up the possibility of
295 // falling off the end of the queue during that time.
296
297 for (FetcherStruct &f : fetchers_) {
298 if (f.wants_writer) {
299 f.writer = log_namer_->MakeWriter(f.channel);
300 }
301 if (f.wants_timestamp_writer) {
302 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
303 }
304 if (f.wants_contents_writer) {
305 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
306 f.channel, CHECK_NOTNULL(f.timestamp_node));
307 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800308 }
309
Brian Silverman1f345222020-09-24 21:14:48 -0700310 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700311 node_state_.resize(configuration::MultiNode(configuration_)
312 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700313 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800314
Austin Schuh2f8fd752020-09-01 22:38:28 -0700315 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700316 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800317
Austin Schuh2f8fd752020-09-01 22:38:28 -0700318 node_state_[node_index].log_file_header = MakeHeader(node);
319 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800320
Austin Schuh2f8fd752020-09-01 22:38:28 -0700321 // Grab data from each channel right before we declare the log file started
322 // so we can capture the latest message on each channel. This lets us have
323 // non periodic messages with configuration that now get logged.
324 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700325 const auto start = event_loop_->monotonic_now();
326 const bool got_new = f.fetcher->Fetch();
327 const auto end = event_loop_->monotonic_now();
328 RecordFetchResult(start, end, got_new, &f);
329
330 // If there is a message, we want to write it.
331 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700332 }
333
334 // Clear out any old timestamps in case we are re-starting logging.
335 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800336 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
337 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700338 }
339
340 WriteHeader();
341
342 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
343 << " start_time " << last_synchronized_time_;
344
Austin Schuh315b96b2020-12-11 21:21:12 -0800345 // Force logging up until the start of the log file now, so the messages at
346 // the start are always ordered before the rest of the messages.
347 // Note: this ship may have already sailed, but we don't have to make it
348 // worse.
349 // TODO(austin): Test...
350 LogUntil(last_synchronized_time_);
351
Austin Schuh2f8fd752020-09-01 22:38:28 -0700352 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
353 polling_period_);
354}
355
Brian Silverman1f345222020-09-24 21:14:48 -0700356std::unique_ptr<LogNamer> Logger::StopLogging(
357 aos::monotonic_clock::time_point end_time) {
358 CHECK(log_namer_) << ": Not logging right now";
359
360 if (end_time != aos::monotonic_clock::min_time) {
361 LogUntil(end_time);
362 }
363 timer_handler_->Disable();
364
365 for (FetcherStruct &f : fetchers_) {
366 f.writer = nullptr;
367 f.timestamp_writer = nullptr;
368 f.contents_writer = nullptr;
369 }
370 node_state_.clear();
371
Brian Silvermanae7c0332020-09-30 16:58:23 -0700372 log_event_uuid_ = UUID::Zero();
373 log_start_uuid_ = std::string();
374
Brian Silverman1f345222020-09-24 21:14:48 -0700375 return std::move(log_namer_);
376}
377
Austin Schuhfa895892020-01-07 20:07:41 -0800378void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700379 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700380 server_statistics_fetcher_.Fetch();
381 }
382
383 aos::monotonic_clock::time_point monotonic_start_time =
384 event_loop_->monotonic_now();
385 aos::realtime_clock::time_point realtime_start_time =
386 event_loop_->realtime_now();
387
388 // We need to pick a point in time to declare the log file "started". This
389 // starts here. It needs to be after everything is fetched so that the
390 // fetchers are all pointed at the most recent message before the start
391 // time.
392 last_synchronized_time_ = monotonic_start_time;
393
Austin Schuh6f3babe2020-01-26 20:34:50 -0800394 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700395 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700396 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
397 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800398 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800399 }
400}
Austin Schuh8bd96322020-02-13 21:18:22 -0800401
Austin Schuh315b96b2020-12-11 21:21:12 -0800402void Logger::MaybeWriteHeader(int node_index) {
403 if (configuration::MultiNode(configuration_)) {
404 return MaybeWriteHeader(node_index,
405 configuration_->nodes()->Get(node_index));
406 } else {
407 return MaybeWriteHeader(node_index, nullptr);
408 }
409}
410
411void Logger::MaybeWriteHeader(int node_index, const Node *node) {
412 // This function is responsible for writing the header when the header both
413 // has valid data, and when it needs to be written.
414 if (node_state_[node_index].header_written &&
415 node_state_[node_index].header_valid) {
416 // The header has been written and is valid, nothing to do.
417 return;
418 }
419 if (!node_state_[node_index].has_source_node_boot_uuid) {
420 // Can't write a header if we don't have the boot UUID.
421 return;
422 }
423
424 // WriteHeader writes the first header in a log file. We want to do this only
425 // once.
426 //
427 // Rotate rewrites the same header with a new part ID, but keeps the same part
428 // UUID. We don't want that when things reboot, because that implies that
429 // parts go together across a reboot.
430 //
431 // Reboot resets the parts UUID. So, once we've written a header the first
432 // time, we want to use Reboot to rotate the log and reset the parts UUID.
433 //
434 // header_valid is cleared whenever the remote reboots.
435 if (node_state_[node_index].header_written) {
436 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
437 } else {
438 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
439
440 node_state_[node_index].header_written = true;
441 }
442 node_state_[node_index].header_valid = true;
443}
444
Austin Schuh2f8fd752020-09-01 22:38:28 -0700445void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700446 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700447 server_statistics_fetcher_.Fetch();
448 } else {
449 return;
450 }
451
452 if (server_statistics_fetcher_.get() == nullptr) {
453 return;
454 }
455
456 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700457 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700458 if (MaybeUpdateTimestamp(
459 node, node_index,
460 server_statistics_fetcher_.context().monotonic_event_time,
461 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800462 CHECK(node_state_[node_index].header_written);
463 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700464 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800465 } else {
466 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700467 }
468 }
469}
470
Austin Schuh315b96b2020-12-11 21:21:12 -0800471void Logger::SetStartTime(
472 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
473 aos::realtime_clock::time_point realtime_start_time,
474 aos::monotonic_clock::time_point logger_monotonic_start_time,
475 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700476 node_state_[node_index].monotonic_start_time = monotonic_start_time;
477 node_state_[node_index].realtime_start_time = realtime_start_time;
478 node_state_[node_index]
479 .log_file_header.mutable_message()
480 ->mutate_monotonic_start_time(
481 std::chrono::duration_cast<std::chrono::nanoseconds>(
482 monotonic_start_time.time_since_epoch())
483 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800484
485 // Add logger start times if they are available in the log file header.
486 if (node_state_[node_index]
487 .log_file_header.mutable_message()
488 ->has_logger_monotonic_start_time()) {
489 node_state_[node_index]
490 .log_file_header.mutable_message()
491 ->mutate_logger_monotonic_start_time(
492 std::chrono::duration_cast<std::chrono::nanoseconds>(
493 logger_monotonic_start_time.time_since_epoch())
494 .count());
495 }
496
497 if (node_state_[node_index]
498 .log_file_header.mutable_message()
499 ->has_logger_realtime_start_time()) {
500 node_state_[node_index]
501 .log_file_header.mutable_message()
502 ->mutate_logger_realtime_start_time(
503 std::chrono::duration_cast<std::chrono::nanoseconds>(
504 logger_realtime_start_time.time_since_epoch())
505 .count());
506 }
507
Austin Schuh2f8fd752020-09-01 22:38:28 -0700508 if (node_state_[node_index]
509 .log_file_header.mutable_message()
510 ->has_realtime_start_time()) {
511 node_state_[node_index]
512 .log_file_header.mutable_message()
513 ->mutate_realtime_start_time(
514 std::chrono::duration_cast<std::chrono::nanoseconds>(
515 realtime_start_time.time_since_epoch())
516 .count());
517 }
518}
519
520bool Logger::MaybeUpdateTimestamp(
521 const Node *node, int node_index,
522 aos::monotonic_clock::time_point monotonic_start_time,
523 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700524 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700525 if (node_state_[node_index].monotonic_start_time !=
526 monotonic_clock::min_time) {
527 return false;
528 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800529 if (event_loop_->node() == node ||
530 !configuration::MultiNode(configuration_)) {
531 // There are no offsets to compute for ourself, so always succeed.
532 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
533 monotonic_start_time, realtime_start_time);
534 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700535 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800536 } else if (server_statistics_fetcher_.get() != nullptr) {
537 // We must be a remote node now. Look for the connection and see if it is
538 // connected.
539
540 for (const message_bridge::ServerConnection *connection :
541 *server_statistics_fetcher_->connections()) {
542 if (connection->node()->name()->string_view() !=
543 node->name()->string_view()) {
544 continue;
545 }
546
547 if (connection->state() != message_bridge::State::CONNECTED) {
548 VLOG(1) << node->name()->string_view()
549 << " is not connected, can't start it yet.";
550 break;
551 }
552
553 // Update the boot UUID as soon as we know we are connected.
554 if (!connection->has_boot_uuid()) {
555 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
556 break;
557 }
558
559 if (!node_state_[node_index].has_source_node_boot_uuid ||
560 node_state_[node_index].source_node_boot_uuid !=
561 connection->boot_uuid()->string_view()) {
562 node_state_[node_index].SetBootUUID(
563 connection->boot_uuid()->string_view());
564 }
565
566 if (!connection->has_monotonic_offset()) {
567 VLOG(1) << "Missing monotonic offset for setting start time for node "
568 << aos::FlatbufferToJson(node);
569 break;
570 }
571
572 // Found it and it is connected. Compensate and go.
573 SetStartTime(node_index,
574 monotonic_start_time +
575 std::chrono::nanoseconds(connection->monotonic_offset()),
576 realtime_start_time, monotonic_start_time,
577 realtime_start_time);
578 return true;
579 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700580 }
581 return false;
582}
583
584aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
585 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800586 // Now write the header with this timestamp in it.
587 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800588 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800589
Austin Schuh2f8fd752020-09-01 22:38:28 -0700590 // TODO(austin): Compress this much more efficiently. There are a bunch of
591 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700592 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700593 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800594
Brian Silvermanae7c0332020-09-30 16:58:23 -0700595 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700596 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800597
Brian Silvermanae7c0332020-09-30 16:58:23 -0700598 CHECK(log_event_uuid_ != UUID::Zero());
599 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
600 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700601
Brian Silvermanae7c0332020-09-30 16:58:23 -0700602 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
603 fbb.CreateString(logger_instance_uuid_.string_view());
604
605 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
606 if (!log_start_uuid_.empty()) {
607 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
608 }
609
Austin Schuh315b96b2020-12-11 21:21:12 -0800610 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
611 fbb.CreateString(event_loop_->boot_uuid().string_view());
612
613 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
614 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700615
616 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700617 fbb.CreateString("00000000-0000-4000-8000-000000000000");
618
Austin Schuhfa895892020-01-07 20:07:41 -0800619 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700620 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700621
Austin Schuh0c297012020-09-16 18:41:59 -0700622 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800623 // TODO(austin): Reuse the node we just copied in above.
624 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
625 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800626 }
627
628 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
629
Austin Schuh64fab802020-09-09 22:47:47 -0700630 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800631
632 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800633 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800634 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700635 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800636 }
637
638 log_file_header_builder.add_configuration(configuration_offset);
639 // The worst case theoretical out of order is the polling period times 2.
640 // One message could get logged right after the boundary, but be for right
641 // before the next boundary. And the reverse could happen for another
642 // message. Report back 3x to be extra safe, and because the cost isn't
643 // huge on the read side.
644 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700645 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800646
647 log_file_header_builder.add_monotonic_start_time(
648 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700649 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800650 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700651 if (node == event_loop_->node()) {
652 log_file_header_builder.add_realtime_start_time(
653 std::chrono::duration_cast<std::chrono::nanoseconds>(
654 realtime_clock::min_time.time_since_epoch())
655 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800656 } else {
657 log_file_header_builder.add_logger_monotonic_start_time(
658 std::chrono::duration_cast<std::chrono::nanoseconds>(
659 monotonic_clock::min_time.time_since_epoch())
660 .count());
661 log_file_header_builder.add_logger_realtime_start_time(
662 std::chrono::duration_cast<std::chrono::nanoseconds>(
663 realtime_clock::min_time.time_since_epoch())
664 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800665 }
666
Brian Silvermanae7c0332020-09-30 16:58:23 -0700667 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
668 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
669 if (!log_start_uuid_offset.IsNull()) {
670 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
671 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800672 log_file_header_builder.add_logger_node_boot_uuid(
673 logger_node_boot_uuid_offset);
674 log_file_header_builder.add_source_node_boot_uuid(
675 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700676
677 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
678 log_file_header_builder.add_parts_index(0);
679
Austin Schuh2f8fd752020-09-01 22:38:28 -0700680 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800681 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
682 fbb.Release());
683
684 CHECK(result.Verify()) << ": Built a corrupted header.";
685
686 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700687}
688
Brian Silvermancb805822020-10-06 17:43:35 -0700689void Logger::ResetStatisics() {
690 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
691 max_message_fetch_time_channel_ = -1;
692 max_message_fetch_time_size_ = -1;
693 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
694 total_message_fetch_count_ = 0;
695 total_message_fetch_bytes_ = 0;
696 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
697 total_nop_fetch_count_ = 0;
698 max_copy_time_ = std::chrono::nanoseconds::zero();
699 max_copy_time_channel_ = -1;
700 max_copy_time_size_ = -1;
701 total_copy_time_ = std::chrono::nanoseconds::zero();
702 total_copy_count_ = 0;
703 total_copy_bytes_ = 0;
704}
705
Austin Schuh2f8fd752020-09-01 22:38:28 -0700706void Logger::Rotate() {
707 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700708 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700709 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700710 }
711}
712
713void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800714 // Grab the latest ServerStatistics message. This will always have the
715 // oppertunity to be >= to the current time, so it will always represent any
716 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700717 WriteMissingTimestamps();
718
719 // Write each channel to disk, one at a time.
720 for (FetcherStruct &f : fetchers_) {
721 while (true) {
722 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700723 const auto start = event_loop_->monotonic_now();
724 const bool got_new = f.fetcher->FetchNext();
725 const auto end = event_loop_->monotonic_now();
726 RecordFetchResult(start, end, got_new, &f);
727 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700728 VLOG(2) << "No new data on "
729 << configuration::CleanedChannelToString(
730 f.fetcher->channel());
731 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700732 }
Brian Silvermancb805822020-10-06 17:43:35 -0700733 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700734 }
735
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700737 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700738 break;
739 }
Brian Silvermancb805822020-10-06 17:43:35 -0700740 if (f.writer != nullptr) {
741 // Write!
742 const auto start = event_loop_->monotonic_now();
743 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
744 max_header_size_);
745 fbb.ForceDefaults(true);
746
747 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
748 f.channel_index, f.log_type));
749 const auto end = event_loop_->monotonic_now();
750 RecordCreateMessageTime(start, end, &f);
751
752 VLOG(2) << "Writing data as node "
753 << FlatbufferToJson(event_loop_->node()) << " for channel "
754 << configuration::CleanedChannelToString(f.fetcher->channel())
755 << " to " << f.writer->filename() << " data "
756 << FlatbufferToJson(
757 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
758 fbb.GetBufferPointer()));
759
760 max_header_size_ = std::max(max_header_size_,
761 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800762 CHECK(node_state_[f.data_node_index].header_valid)
763 << ": Can't write data before the header on channel "
764 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700765 f.writer->QueueSizedFlatbuffer(&fbb);
766 }
767
768 if (f.timestamp_writer != nullptr) {
769 // And now handle timestamps.
770 const auto start = event_loop_->monotonic_now();
771 flatbuffers::FlatBufferBuilder fbb;
772 fbb.ForceDefaults(true);
773
774 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
775 f.channel_index,
776 LogType::kLogDeliveryTimeOnly));
777 const auto end = event_loop_->monotonic_now();
778 RecordCreateMessageTime(start, end, &f);
779
780 VLOG(2) << "Writing timestamps as node "
781 << FlatbufferToJson(event_loop_->node()) << " for channel "
782 << configuration::CleanedChannelToString(f.fetcher->channel())
783 << " to " << f.timestamp_writer->filename() << " timestamp "
784 << FlatbufferToJson(
785 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
786 fbb.GetBufferPointer()));
787
Austin Schuh315b96b2020-12-11 21:21:12 -0800788 CHECK(node_state_[f.timestamp_node_index].header_valid)
789 << ": Can't write data before the header on channel "
790 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700791 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
792 }
793
794 if (f.contents_writer != nullptr) {
795 const auto start = event_loop_->monotonic_now();
796 // And now handle the special message contents channel. Copy the
797 // message into a FlatBufferBuilder and save it to disk.
798 // TODO(austin): We can be more efficient here when we start to
799 // care...
800 flatbuffers::FlatBufferBuilder fbb;
801 fbb.ForceDefaults(true);
802
Austin Schuh0de30f32020-12-06 12:44:28 -0800803 const RemoteMessage *msg =
804 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700805
Austin Schuh315b96b2020-12-11 21:21:12 -0800806 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
807 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
808 node_state_[f.contents_node_index].source_node_boot_uuid !=
809 msg->boot_uuid()->string_view()) {
810 node_state_[f.contents_node_index].SetBootUUID(
811 msg->boot_uuid()->string_view());
812
813 MaybeWriteHeader(f.contents_node_index);
814 }
815
Brian Silvermancb805822020-10-06 17:43:35 -0700816 logger::MessageHeader::Builder message_header_builder(fbb);
817
818 // TODO(austin): This needs to check the channel_index and confirm
819 // that it should be logged before squirreling away the timestamp to
820 // disk. We don't want to log irrelevant timestamps.
821
822 // Note: this must match the same order as MessageBridgeServer and
823 // PackMessage. We want identical headers to have identical
824 // on-the-wire formats to make comparing them easier.
825
826 // Translate from the channel index that the event loop uses to the
827 // channel index in the log file.
828 message_header_builder.add_channel_index(
829 event_loop_to_logged_channel_index_[msg->channel_index()]);
830
831 message_header_builder.add_queue_index(msg->queue_index());
832 message_header_builder.add_monotonic_sent_time(
833 msg->monotonic_sent_time());
834 message_header_builder.add_realtime_sent_time(
835 msg->realtime_sent_time());
836
837 message_header_builder.add_monotonic_remote_time(
838 msg->monotonic_remote_time());
839 message_header_builder.add_realtime_remote_time(
840 msg->realtime_remote_time());
841 message_header_builder.add_remote_queue_index(
842 msg->remote_queue_index());
843
844 fbb.FinishSizePrefixed(message_header_builder.Finish());
845 const auto end = event_loop_->monotonic_now();
846 RecordCreateMessageTime(start, end, &f);
847
Austin Schuh315b96b2020-12-11 21:21:12 -0800848 CHECK(node_state_[f.contents_node_index].header_valid)
849 << ": Can't write data before the header on channel "
850 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700851 f.contents_writer->QueueSizedFlatbuffer(&fbb);
852 }
853
854 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700855 }
856 }
857 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800858}
859
Brian Silverman1f345222020-09-24 21:14:48 -0700860void Logger::DoLogData(const monotonic_clock::time_point end_time) {
861 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800862 // max_out_of_order_duration. To do this, we need sync points. Every write
863 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800864
865 do {
866 // Move the sync point up by at most polling_period. This forces one sync
867 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700868 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
869
870 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800871
Austin Schuhe309d2a2019-11-29 13:25:21 -0800872 // If we missed cycles, we could be pretty far behind. Spin until we are
873 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700874 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800875}
876
Brian Silvermancb805822020-10-06 17:43:35 -0700877void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
878 aos::monotonic_clock::time_point end,
879 bool got_new, FetcherStruct *fetcher) {
880 const auto duration = end - start;
881 if (!got_new) {
882 ++total_nop_fetch_count_;
883 total_nop_fetch_time_ += duration;
884 return;
885 }
886 ++total_message_fetch_count_;
887 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
888 total_message_fetch_time_ += duration;
889 if (duration > max_message_fetch_time_) {
890 max_message_fetch_time_ = duration;
891 max_message_fetch_time_channel_ = fetcher->channel_index;
892 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
893 }
894}
895
896void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
897 aos::monotonic_clock::time_point end,
898 FetcherStruct *fetcher) {
899 const auto duration = end - start;
900 total_copy_time_ += duration;
901 ++total_copy_count_;
902 total_copy_bytes_ += fetcher->fetcher->context().size;
903 if (duration > max_copy_time_) {
904 max_copy_time_ = duration;
905 max_copy_time_channel_ = fetcher->channel_index;
906 max_copy_time_size_ = fetcher->fetcher->context().size;
907 }
908}
909
Austin Schuh11d43732020-09-21 17:28:30 -0700910std::vector<std::vector<std::string>> ToLogReaderVector(
911 const std::vector<LogFile> &log_files) {
912 std::vector<std::vector<std::string>> result;
913 for (const LogFile &log_file : log_files) {
914 for (const LogParts &log_parts : log_file.parts) {
915 std::vector<std::string> parts;
916 for (const std::string &part : log_parts.parts) {
917 parts.emplace_back(part);
918 }
919 result.emplace_back(std::move(parts));
920 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700921 }
922 return result;
923}
924
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800925LogReader::LogReader(std::string_view filename,
926 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800927 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800928
Austin Schuh287d43d2020-12-04 20:19:33 -0800929LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800930 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800931 : log_files_(std::move(log_files)),
932 log_file_header_(MaybeReadHeaderOrDie(log_files_)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800933 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800934 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800935
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700936 // Remap all existing remote timestamp channels. They will be recreated, and
937 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700938 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700939 std::vector<const Node *> timestamp_logger_nodes =
940 configuration::TimestampNodes(logged_configuration(), node);
941 for (const Node *remote_node : timestamp_logger_nodes) {
942 const std::string channel = absl::StrCat(
943 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800944 // See if the log file is an old log with MessageHeader channels in it, or
945 // a newer log with RemoteMessage. If we find an older log, rename the
946 // type too along with the name.
947 if (HasChannel<MessageHeader>(channel, node)) {
948 CHECK(!HasChannel<RemoteMessage>(channel, node))
949 << ": Can't have both a MessageHeader and RemoteMessage remote "
950 "timestamp channel.";
951 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
952 "aos.message_bridge.RemoteMessage");
953 } else {
954 CHECK(HasChannel<RemoteMessage>(channel, node))
955 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
956 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
957 << node->name()->string_view();
958 RemapLoggedChannel<RemoteMessage>(channel, node);
959 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700960 }
961 }
962
Austin Schuh6aa77be2020-02-22 21:06:40 -0800963 if (replay_configuration) {
964 CHECK_EQ(configuration::MultiNode(configuration()),
965 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700966 << ": Log file and replay config need to both be multi or single "
967 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800968 }
969
Austin Schuh6f3babe2020-01-26 20:34:50 -0800970 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800971 states_.emplace_back(std::make_unique<State>(
972 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800973 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800974 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700975 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800976 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700977 << ": Log file and replay config need to have matching nodes "
978 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700979 for (const Node *node : *logged_configuration()->nodes()) {
980 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700981 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
982 << " in logged config that is not present in the replay "
983 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700984 }
985 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800986 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800987 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800988 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800989}
990
Austin Schuh6aa77be2020-02-22 21:06:40 -0800991LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700992 if (event_loop_factory_unique_ptr_) {
993 Deregister();
994 } else if (event_loop_factory_ != nullptr) {
995 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
996 "is destroyed";
997 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700998 // Zero out some buffers. It's easy to do use-after-frees on these, so make
999 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001000 if (remapped_configuration_buffer_) {
1001 remapped_configuration_buffer_->Wipe();
1002 }
1003 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -08001004}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001005
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001006const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001007 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001008}
1009
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001010const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001011 return remapped_configuration_;
1012}
1013
Austin Schuh6f3babe2020-01-26 20:34:50 -08001014std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001015 // Because the Node pointer will only be valid if it actually points to
1016 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001017 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001018 //
1019 // Also, note, that when ever a map is changed, the nodes in here are
1020 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001021 CHECK(remapped_configuration_ != nullptr)
1022 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001023 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001024}
Austin Schuh15649d62019-12-28 16:36:38 -08001025
Austin Schuh11d43732020-09-21 17:28:30 -07001026monotonic_clock::time_point LogReader::monotonic_start_time(
1027 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001028 State *state =
1029 states_[configuration::GetNodeIndex(configuration(), node)].get();
1030 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1031
Austin Schuh858c9f32020-08-31 16:56:12 -07001032 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001033}
1034
Austin Schuh11d43732020-09-21 17:28:30 -07001035realtime_clock::time_point LogReader::realtime_start_time(
1036 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001037 State *state =
1038 states_[configuration::GetNodeIndex(configuration(), node)].get();
1039 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1040
Austin Schuh858c9f32020-08-31 16:56:12 -07001041 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001042}
1043
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001044void LogReader::Register() {
1045 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001046 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001047 Register(event_loop_factory_unique_ptr_.get());
1048}
1049
Austin Schuh92547522019-12-28 14:33:43 -08001050void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001051 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001052 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001053 filters_ =
1054 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
1055 event_loop_factory_);
Austin Schuh92547522019-12-28 14:33:43 -08001056
Brian Silvermand90905f2020-09-23 14:42:56 -07001057 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001058 const size_t node_index =
1059 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001060 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1061 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001062
1063 // Confirm that all the parts are from the same boot if there are enough
1064 // parts to not be from the same boot.
1065 if (filtered_parts.size() > 1u) {
1066 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1067 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1068 filtered_parts[0].source_boot_uuid)
1069 << ": Found parts from different boots "
1070 << LogFileVectorToString(log_files_);
1071 }
1072 }
1073
Austin Schuh287d43d2020-12-04 20:19:33 -08001074 states_[node_index] = std::make_unique<State>(
1075 filtered_parts.size() == 0u
1076 ? nullptr
1077 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001078 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001079 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001080 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001081
1082 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001083 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001084
Austin Schuh287d43d2020-12-04 20:19:33 -08001085 for (const Node *node : configuration::GetNodes(configuration())) {
1086 const size_t node_index =
1087 configuration::GetNodeIndex(configuration(), node);
1088 State *state = states_[node_index].get();
1089 for (const Node *other_node : configuration::GetNodes(configuration())) {
1090 const size_t other_node_index =
1091 configuration::GetNodeIndex(configuration(), other_node);
1092 State *other_state = states_[other_node_index].get();
1093 if (other_state != state) {
1094 state->AddPeer(other_state);
1095 }
1096 }
1097 }
1098
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001099 // Register after making all the State objects so we can build references
1100 // between them.
1101 for (const Node *node : configuration::GetNodes(configuration())) {
1102 const size_t node_index =
1103 configuration::GetNodeIndex(configuration(), node);
1104 State *state = states_[node_index].get();
1105
1106 Register(state->event_loop());
1107 }
1108
James Kuszmaul46d82582020-05-09 19:50:09 -07001109 if (live_nodes_ == 0) {
1110 LOG(FATAL)
1111 << "Don't have logs from any of the nodes in the replay config--are "
1112 "you sure that the replay config matches the original config?";
1113 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001114
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001115 filters_->Initialize(logged_configuration());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001116
Austin Schuh858c9f32020-08-31 16:56:12 -07001117 for (std::unique_ptr<State> &state : states_) {
1118 state->SeedSortedMessages();
1119 }
1120
Austin Schuh2f8fd752020-09-01 22:38:28 -07001121 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001122 UpdateOffsets();
1123
Austin Schuh2f8fd752020-09-01 22:38:28 -07001124 // We want to start the log file at the last start time of the log files
1125 // from all the nodes. Compute how long each node's simulation needs to run
1126 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001127 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001128
Austin Schuh2f8fd752020-09-01 22:38:28 -07001129 // TODO(austin): We want an "OnStart" callback for each node rather than
1130 // running until the last node.
1131
Austin Schuh8bd96322020-02-13 21:18:22 -08001132 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001133 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1134 << MaybeNodeName(state->event_loop()->node()) << "now "
1135 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001136 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1137 continue;
1138 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001139 // And start computing the start time on the distributed clock now that
1140 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001141 start_time = std::max(
1142 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001143 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001144
1145 CHECK_GE(start_time, distributed_clock::epoch())
1146 << ": Hmm, we have a node starting before the start of time. Offset "
1147 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001148
Austin Schuh6f3babe2020-01-26 20:34:50 -08001149 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1150 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001151 // nodes, and also replayed on the other nodes. This may not satisfy all
1152 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001153 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1154 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1155 const Channel *channel = logged_configuration()->channels()->Get(i);
1156 const Node *node = configuration::GetNode(
1157 configuration(), channel->source_node()->string_view());
1158
Austin Schuh8bd96322020-02-13 21:18:22 -08001159 State *state =
1160 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001161
1162 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001163 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001164
1165 event_loop_factory_->DisableForwarding(remapped_channel);
1166 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001167
1168 // If we are replaying a log, we don't want a bunch of redundant messages
1169 // from both the real message bridge and simulated message bridge.
1170 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001171 }
1172
Austin Schuhcde938c2020-02-02 17:30:07 -08001173 // While we are starting the system up, we might be relying on matching data
1174 // to timestamps on log files where the timestamp log file starts before the
1175 // data. In this case, it is reasonable to expect missing data.
1176 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001177 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001178 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001179 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001180 // Now that we are running for real, missing data means that the log file is
1181 // corrupted or went wrong.
1182 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001183
Austin Schuh8bd96322020-02-13 21:18:22 -08001184 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001185 // Make the RT clock be correct before handing it to the user.
1186 if (state->realtime_start_time() != realtime_clock::min_time) {
1187 state->SetRealtimeOffset(state->monotonic_start_time(),
1188 state->realtime_start_time());
1189 }
1190 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1191 << MaybeNodeName(state->event_loop()->node()) << "now "
1192 << state->monotonic_now();
1193 }
1194
1195 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001196 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -08001197 }
1198}
1199
Austin Schuh2f8fd752020-09-01 22:38:28 -07001200void LogReader::UpdateOffsets() {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001201 filters_->UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001202
1203 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001204 filters_->LogFit("Offset is");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205 }
1206}
1207
1208message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001209 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001210 if (filters_) {
1211 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001212 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001213 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001214}
1215
Austin Schuhe309d2a2019-11-29 13:25:21 -08001216void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001217 State *state =
1218 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1219 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001220
Austin Schuh858c9f32020-08-31 16:56:12 -07001221 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001222
Tyler Chatow67ddb032020-01-12 14:30:04 -08001223 // We don't run timing reports when trying to print out logged data, because
1224 // otherwise we would end up printing out the timing reports themselves...
1225 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001226 event_loop->SkipTimingReport();
1227 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001228
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001229 for (size_t logged_channel_index = 0;
1230 logged_channel_index < logged_configuration()->channels()->size();
1231 ++logged_channel_index) {
1232 const Channel *channel = RemapChannel(
1233 event_loop,
1234 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001235
Austin Schuh2f8fd752020-09-01 22:38:28 -07001236 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001237 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001238
1239 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001240
1241 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1242 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001243 // We've got a message which is being forwarded to this node.
1244 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001245 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001246 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001247
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001248 // Delivery timestamps are supposed to be logged back on the source node.
1249 // Configure remote timestamps to be sent.
1250 const bool delivery_time_is_logged =
1251 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1252 channel, event_loop->node(), source_node);
1253
1254 source_state =
1255 states_[configuration::GetNodeIndex(configuration(), source_node)]
1256 .get();
1257
1258 if (delivery_time_is_logged) {
1259 remote_timestamp_sender =
1260 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001261 }
1262 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001263
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001264 state->SetChannel(
1265 logged_channel_index,
1266 configuration::ChannelIndex(event_loop->configuration(), channel),
1267 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1268 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001269 }
1270
Austin Schuh6aa77be2020-02-22 21:06:40 -08001271 // If we didn't find any log files with data in them, we won't ever get a
1272 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001273 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001274 return;
1275 }
1276
Austin Schuh858c9f32020-08-31 16:56:12 -07001277 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001278 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1279 << "at " << state->event_loop()->context().monotonic_event_time
1280 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001281 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001282 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001283 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001284 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001285 event_loop_factory_->Exit();
1286 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001287 return;
1288 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001289 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001290 filters_->LogFit("Offset was");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001291 }
1292
1293 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001294 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001295
Austin Schuhe309d2a2019-11-29 13:25:21 -08001296 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001297 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001298 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001299 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001300 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1301 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001302 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001303 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001304 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001305 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001306 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001307 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001308 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001309 << "): " << FlatbufferToJson(state->event_loop()->node())
1310 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001311 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001312 << state->DebugString();
1313 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001314
Austin Schuh287d43d2020-12-04 20:19:33 -08001315 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001316 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001317 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001318 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001319 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001320 timestamped_message.data.span().size() != 0u) {
1321 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001322 << ": Got a message without data on channel "
1323 << configuration::CleanedChannelToString(
1324 logged_configuration()->channels()->Get(
1325 timestamped_message.channel_index))
1326 << ". Forwarding entry which was not matched? Use "
1327 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001328
Austin Schuh2f8fd752020-09-01 22:38:28 -07001329 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001330 // Confirm that the message was sent on the sending node before the
1331 // destination node (this node). As a proxy, do this by making sure
1332 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001333 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001334 CHECK_LT(
1335 timestamped_message.monotonic_remote_time,
1336 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001337 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001338 << state->remote_node(timestamped_message.channel_index)
1339 ->name()
1340 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001341 << " while trying to send a message on "
1342 << configuration::CleanedChannelToString(
1343 logged_configuration()->channels()->Get(
1344 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001345 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001346 } else if (timestamped_message.monotonic_remote_time >=
1347 state->monotonic_remote_now(
1348 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001349 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001350 << "Check failed: timestamped_message.monotonic_remote_time < "
1351 "state->monotonic_remote_now(timestamped_message.channel_"
1352 "index) ("
1353 << timestamped_message.monotonic_remote_time << " vs. "
1354 << state->monotonic_remote_now(
1355 timestamped_message.channel_index)
1356 << ") " << state->event_loop()->node()->name()->string_view()
1357 << " to "
1358 << state->remote_node(timestamped_message.channel_index)
1359 ->name()
1360 ->string_view()
1361 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001362 << " ("
1363 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001365 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001366 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001367 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001368 timestamped_message.channel_index,
1369 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001370 << ") " << state->DebugString();
1371 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001372 }
1373
Austin Schuh15649d62019-12-28 16:36:38 -08001374 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001375 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1376 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001377
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001379 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001380 // TODO(austin): std::move channel_data in and make that efficient in
1381 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001382 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001383 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001384 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001385 // reading the rest of the log file and call it quits. We don't want
1386 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001387 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1388 bool update_time_dummy;
1389 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001390 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001391 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001392 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001393 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001394 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001395 LOG(WARNING)
1396 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001397 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001398 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001399 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001400 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001401 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001402 }
1403
Austin Schuh858c9f32020-08-31 16:56:12 -07001404 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001405 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001406 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1407 << "wakeup for " << next_time << "("
1408 << state->ToDistributedClock(next_time)
1409 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001410 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001411 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001412 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1413 << "No next message, scheduling shutdown";
1414 // Set a timer up immediately after now to die. If we don't do this,
1415 // then the senders waiting on the message we just read will never get
1416 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001417 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001418 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1419 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001420 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001421 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001422
Austin Schuh2f8fd752020-09-01 22:38:28 -07001423 // Once we make this call, the current time changes. So do everything
1424 // which involves time before changing it. That especially includes
1425 // sending the message.
1426 if (update_time) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001427 filters_->LogFit("");
1428
Austin Schuh2f8fd752020-09-01 22:38:28 -07001429 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1430 << "updating offsets";
1431
1432 std::vector<aos::monotonic_clock::time_point> before_times;
1433 before_times.resize(states_.size());
1434 std::transform(states_.begin(), states_.end(), before_times.begin(),
1435 [](const std::unique_ptr<State> &state) {
1436 return state->monotonic_now();
1437 });
1438
1439 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001440 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1441 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001442 }
1443
Austin Schuh8bd96322020-02-13 21:18:22 -08001444 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001445 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1446 << state->monotonic_now();
1447
1448 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001449 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1450 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001451 }
1452
1453 // TODO(austin): We should be perfect.
1454 const std::chrono::nanoseconds kTolerance{3};
1455 if (!FLAGS_skip_order_validation) {
1456 CHECK_GE(next_time, state->monotonic_now())
1457 << ": Time skipped the next event.";
1458
1459 for (size_t i = 0; i < states_.size(); ++i) {
1460 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1461 << ": Time changed too much on node "
1462 << MaybeNodeName(states_[i]->event_loop()->node());
1463 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1464 << ": Time changed too much on node "
1465 << states_[i]->event_loop()->node()->name()->string_view();
1466 }
1467 } else {
1468 if (next_time < state->monotonic_now()) {
1469 LOG(WARNING) << "Check failed: next_time >= "
1470 "state->monotonic_now() ("
1471 << next_time << " vs. " << state->monotonic_now()
1472 << "): Time skipped the next event.";
1473 }
1474 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001475 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001476 LOG(WARNING) << "Check failed: "
1477 "states_[i]->monotonic_now() "
1478 ">= before_times[i] - kTolerance ("
1479 << states_[i]->monotonic_now() << " vs. "
1480 << before_times[i] - kTolerance
1481 << ") : Time changed too much on node "
1482 << MaybeNodeName(states_[i]->event_loop()->node());
1483 }
Austin Schuh724032b2020-12-18 22:54:59 -08001484 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001485 LOG(WARNING) << "Check failed: "
1486 "states_[i]->monotonic_now() "
1487 "<= before_times[i] + kTolerance ("
1488 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001489 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001490 << ") : Time changed too much on node "
1491 << MaybeNodeName(states_[i]->event_loop()->node());
1492 }
1493 }
1494 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001495 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001496
1497 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1498 << state->event_loop()->context().monotonic_event_time << " now "
1499 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001500 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001501
Austin Schuh6f3babe2020-01-26 20:34:50 -08001502 ++live_nodes_;
1503
Austin Schuh858c9f32020-08-31 16:56:12 -07001504 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1505 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001506 }
1507}
1508
1509void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001510 // Make sure that things get destroyed in the correct order, rather than
1511 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001512 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001513 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001514 }
Austin Schuh92547522019-12-28 14:33:43 -08001515
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001516 event_loop_factory_unique_ptr_.reset();
1517 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001518}
1519
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001520void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001521 std::string_view add_prefix,
1522 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001523 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1524 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1525 if (channel->name()->str() == name &&
1526 channel->type()->string_view() == type) {
1527 CHECK_EQ(0u, remapped_channels_.count(ii))
1528 << "Already remapped channel "
1529 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001530 RemappedChannel remapped_channel;
1531 remapped_channel.remapped_name =
1532 std::string(add_prefix) + std::string(name);
1533 remapped_channel.new_type = new_type;
1534 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001535 VLOG(1) << "Remapping channel "
1536 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001537 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001538 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001539 return;
1540 }
1541 }
1542 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1543 << type;
1544}
1545
Austin Schuh01b4c352020-09-21 23:09:39 -07001546void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1547 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001548 std::string_view add_prefix,
1549 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001550 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1551 const Channel *remapped_channel =
1552 configuration::GetChannel(logged_configuration(), name, type, "", node);
1553 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1554 << "\", \"type\": \"" << type << "\"}";
1555 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1556 << "\"}";
1557 VLOG(1) << "Remapped "
1558 << aos::configuration::StrippedChannelToString(remapped_channel);
1559
1560 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1561 // we want it to degrade if the heuristics fail to just work.
1562 //
1563 // The easiest way to do this is going to be incredibly specific and verbose.
1564 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1565 // /original/0/spray. Then, create a map from /original/spray to
1566 // /original/0/spray for just the type we were asked for.
1567 if (name != remapped_channel->name()->string_view()) {
1568 MapT new_map;
1569 new_map.match = std::make_unique<ChannelT>();
1570 new_map.match->name = absl::StrCat(add_prefix, name);
1571 new_map.match->type = type;
1572 if (node != nullptr) {
1573 new_map.match->source_node = node->name()->str();
1574 }
1575 new_map.rename = std::make_unique<ChannelT>();
1576 new_map.rename->name =
1577 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1578 maps_.emplace_back(std::move(new_map));
1579 }
1580
1581 const size_t channel_index =
1582 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1583 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1584 << "Already remapped channel "
1585 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001586
1587 RemappedChannel remapped_channel_struct;
1588 remapped_channel_struct.remapped_name =
1589 std::string(add_prefix) +
1590 std::string(remapped_channel->name()->string_view());
1591 remapped_channel_struct.new_type = new_type;
1592 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001593 MakeRemappedConfig();
1594}
1595
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001596void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001597 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001598 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001599 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001600 << ": Can't change the mapping after the events are scheduled.";
1601 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001602 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001603
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001604 // If no remapping occurred and we are using the original config, then there
1605 // is nothing interesting to do here.
1606 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001607 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001608 return;
1609 }
1610 // Config to copy Channel definitions from. Use the specified
1611 // replay_configuration_ if it has been provided.
1612 const Configuration *const base_config = replay_configuration_ == nullptr
1613 ? logged_configuration()
1614 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001615
1616 // Create a config with all the channels, but un-sorted/merged. Collect up
1617 // the schemas while we do this. Call MergeConfiguration to sort everything,
1618 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001619
1620 // This is the builder that we use for the config containing all the new
1621 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001622 flatbuffers::FlatBufferBuilder fbb;
1623 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001624 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001625
1626 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1627 << ": Merging logic needs to be updated when the number of channel "
1628 "fields changes.";
1629
1630 // List of schemas.
1631 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1632 // Make sure our new RemoteMessage schema is in there for old logs without it.
1633 schema_map.insert(std::make_pair(
1634 RemoteMessage::GetFullyQualifiedName(),
1635 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1636 message_bridge::RemoteMessageSchema()))));
1637
1638 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001639 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001640 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001641 base_config, logged_configuration()->channels()->Get(pair.first), "",
1642 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001643 channel_offsets.emplace_back(
1644 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001645 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001646
Austin Schuh0de30f32020-12-06 12:44:28 -08001647 // Now reconstruct the original channels, translating types as needed
1648 for (const Channel *c : *base_config->channels()) {
1649 // Search for a mapping channel.
1650 std::string_view new_type = "";
1651 for (auto &pair : remapped_channels_) {
1652 const Channel *const remapped_channel =
1653 logged_configuration()->channels()->Get(pair.first);
1654 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1655 remapped_channel->type()->string_view() == c->type()->string_view()) {
1656 new_type = pair.second.new_type;
1657 break;
1658 }
1659 }
1660
1661 // Copy everything over.
1662 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1663
1664 // Add the schema if it doesn't exist.
1665 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1666 CHECK(c->has_schema());
1667 schema_map.insert(std::make_pair(c->type()->string_view(),
1668 RecursiveCopyFlatBuffer(c->schema())));
1669 }
1670 }
1671
1672 // The MergeConfiguration API takes a vector, not a map. Convert.
1673 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1674 while (!schema_map.empty()) {
1675 schemas.emplace_back(std::move(schema_map.begin()->second));
1676 schema_map.erase(schema_map.begin());
1677 }
1678
1679 // Create the Configuration containing the new channels that we want to add.
1680 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1681 channels_offset =
1682 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1683
1684 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001685 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001686 if (base_config->maps()) {
1687 for (const Map *map : *base_config->maps()) {
1688 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1689 }
1690 }
1691
1692 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001693 for (const MapT &map : maps_) {
1694 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001695 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001696 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001697 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001698 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001699 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001700 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1701 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001702 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001703 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001704 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001705 match_builder.add_name(match_name_offset);
1706 match_builder.add_type(match_type_offset);
1707 if (!map.match->source_node.empty()) {
1708 match_builder.add_source_node(match_source_node_offset);
1709 }
1710 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1711
Austin Schuh0de30f32020-12-06 12:44:28 -08001712 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001713 rename_builder.add_name(rename_name_offset);
1714 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1715
Austin Schuh0de30f32020-12-06 12:44:28 -08001716 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001717 map_builder.add_match(match_offset);
1718 map_builder.add_rename(rename_offset);
1719 map_offsets.emplace_back(map_builder.Finish());
1720 }
1721
Austin Schuh0de30f32020-12-06 12:44:28 -08001722 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1723 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001724
Austin Schuh0de30f32020-12-06 12:44:28 -08001725 // And copy everything else over.
1726 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1727 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1728
1729 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1730 applications_offset =
1731 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1732
1733 // Now insert everything else in unmodified.
1734 ConfigurationBuilder configuration_builder(fbb);
1735 if (!channels_offset.IsNull()) {
1736 configuration_builder.add_channels(channels_offset);
1737 }
1738 if (!maps_offsets.IsNull()) {
1739 configuration_builder.add_maps(maps_offsets);
1740 }
1741 if (!nodes_offset.IsNull()) {
1742 configuration_builder.add_nodes(nodes_offset);
1743 }
1744 if (!applications_offset.IsNull()) {
1745 configuration_builder.add_applications(applications_offset);
1746 }
1747
1748 if (base_config->has_channel_storage_duration()) {
1749 configuration_builder.add_channel_storage_duration(
1750 base_config->channel_storage_duration());
1751 }
1752
1753 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1754 << ": Merging logic needs to be updated when the number of configuration "
1755 "fields changes.";
1756
1757 fbb.Finish(configuration_builder.Finish());
1758
1759 // Clean it up and return it! By using MergeConfiguration here, we'll
1760 // actually get a deduplicated config for free too.
1761 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1762 configuration::MergeConfiguration(
1763 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1764
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001765 remapped_configuration_buffer_ =
1766 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001767 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001768
1769 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001770
1771 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001772}
1773
Austin Schuh6f3babe2020-01-26 20:34:50 -08001774const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1775 const Channel *channel) {
1776 std::string_view channel_name = channel->name()->string_view();
1777 std::string_view channel_type = channel->type()->string_view();
1778 const int channel_index =
1779 configuration::ChannelIndex(logged_configuration(), channel);
1780 // If the channel is remapped, find the correct channel name to use.
1781 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001782 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001783 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001784 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001785 }
1786
Austin Schuhee711052020-08-24 16:06:09 -07001787 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001788 const Channel *remapped_channel = configuration::GetChannel(
1789 event_loop->configuration(), channel_name, channel_type,
1790 event_loop->name(), event_loop->node());
1791
1792 CHECK(remapped_channel != nullptr)
1793 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1794 << channel_type << "\"} because it is not in the provided configuration.";
1795
1796 return remapped_channel;
1797}
1798
Austin Schuh287d43d2020-12-04 20:19:33 -08001799LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1800 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1801
1802void LogReader::State::AddPeer(State *peer) {
1803 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1804 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1805 }
1806}
Austin Schuh858c9f32020-08-31 16:56:12 -07001807
1808EventLoop *LogReader::State::SetNodeEventLoopFactory(
1809 NodeEventLoopFactory *node_event_loop_factory) {
1810 node_event_loop_factory_ = node_event_loop_factory;
1811 event_loop_unique_ptr_ =
1812 node_event_loop_factory_->MakeEventLoop("log_reader");
1813 return event_loop_unique_ptr_.get();
1814}
1815
1816void LogReader::State::SetChannelCount(size_t count) {
1817 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001818 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001819 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001820 channel_source_state_.resize(count);
1821 factory_channel_index_.resize(count);
1822 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001823}
1824
1825void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001826 size_t logged_channel_index, size_t factory_channel_index,
1827 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001828 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08001829 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001830 channels_[logged_channel_index] = std::move(sender);
1831 filters_[logged_channel_index] = filter;
1832 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1833
1834 if (source_state) {
1835 channel_source_state_[logged_channel_index] = source_state;
1836
1837 if (remote_timestamp_sender != nullptr) {
1838 source_state->queue_index_map_[logged_channel_index] =
1839 std::make_unique<std::vector<State::SentTimestamp>>();
1840 }
1841 }
1842
1843 factory_channel_index_[logged_channel_index] = factory_channel_index;
1844}
1845
Austin Schuh287d43d2020-12-04 20:19:33 -08001846bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1847 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001848 uint32_t remote_queue_index = 0xffffffff;
1849
Austin Schuh287d43d2020-12-04 20:19:33 -08001850 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
1851 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
1852 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1853 ->queue_index_map_[timestamped_message.channel_index]
1854 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001855
1856 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08001857 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
1858 search.realtime_event_time = timestamped_message.realtime_remote_time;
1859 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001860
1861 // Find the sent time if available.
1862 auto element = std::lower_bound(
1863 queue_index_map->begin(), queue_index_map->end(), search,
1864 [](SentTimestamp a, SentTimestamp b) {
1865 if (b.monotonic_event_time < a.monotonic_event_time) {
1866 return false;
1867 }
1868 if (b.monotonic_event_time > a.monotonic_event_time) {
1869 return true;
1870 }
1871
1872 if (b.queue_index < a.queue_index) {
1873 return false;
1874 }
1875 if (b.queue_index > a.queue_index) {
1876 return true;
1877 }
1878
1879 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1880 return false;
1881 });
1882
1883 // TODO(austin): Be a bit more principled here, but we will want to do that
1884 // after the logger rewrite. We hit this when one node finishes, but the
1885 // other node isn't done yet. So there is no send time, but there is a
1886 // receive time.
1887 if (element != queue_index_map->end()) {
1888 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001889 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001890 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001891 timestamped_message.realtime_remote_time);
1892 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001893
1894 remote_queue_index = element->actual_queue_index;
1895 }
1896 }
1897
1898 // Send! Use the replayed queue index here instead of the logged queue index
1899 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001900 const bool sent = sender->Send(
1901 timestamped_message.data.message().data()->Data(),
1902 timestamped_message.data.message().data()->size(),
1903 timestamped_message.monotonic_remote_time,
1904 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001905 if (!sent) return false;
1906
Austin Schuh287d43d2020-12-04 20:19:33 -08001907 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001908 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08001909 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
1910 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
1911 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001912 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08001913 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1914 timestamp);
1915 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1916 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001917 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08001918 remote_timestamp_senders_[timestamped_message.channel_index]
1919 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001920
Austin Schuh315b96b2020-12-11 21:21:12 -08001921 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
1922 builder.fbb()->CreateString(event_loop_->boot_uuid().string_view());
1923
Austin Schuh0de30f32020-12-06 12:44:28 -08001924 RemoteMessage::Builder message_header_builder =
1925 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001926
1927 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001928 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929
1930 // Swap the remote and sent metrics. They are from the sender's
1931 // perspective, not the receiver's perspective.
1932 message_header_builder.add_monotonic_sent_time(
1933 sender->monotonic_sent_time().time_since_epoch().count());
1934 message_header_builder.add_realtime_sent_time(
1935 sender->realtime_sent_time().time_since_epoch().count());
1936 message_header_builder.add_queue_index(sender->sent_queue_index());
1937
1938 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001939 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001940 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001941 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001942
1943 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001944 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001945
1946 builder.Send(message_header_builder.Finish());
1947 }
1948
1949 return true;
1950}
1951
Austin Schuh0de30f32020-12-06 12:44:28 -08001952aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001953 const Node *delivered_node) {
1954 auto sender = remote_timestamp_senders_map_.find(delivered_node);
1955
1956 if (sender == remote_timestamp_senders_map_.end()) {
1957 sender = remote_timestamp_senders_map_
1958 .emplace(std::make_pair(
1959 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001960 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001961 absl::StrCat("/aos/remote_timestamps/",
1962 delivered_node->name()->string_view()))))
1963 .first;
1964 }
1965
1966 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07001967}
1968
Austin Schuh287d43d2020-12-04 20:19:33 -08001969TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001970 CHECK_GT(sorted_messages_.size(), 0u);
1971
Austin Schuh287d43d2020-12-04 20:19:33 -08001972 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001973 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001974 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001975 << std::get<0>(result).monotonic_event_time;
1976 sorted_messages_.pop_front();
1977 SeedSortedMessages();
1978
Austin Schuh287d43d2020-12-04 20:19:33 -08001979 if (std::get<1>(result) != nullptr) {
1980 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07001981 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1982 } else {
1983 *update_time = false;
1984 }
Austin Schuh287d43d2020-12-04 20:19:33 -08001985 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07001986}
1987
1988monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1989 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001990 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001991 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1992 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1993 }
1994
Austin Schuh287d43d2020-12-04 20:19:33 -08001995 TimestampedMessage *m =
1996 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
1997 if (m == nullptr) {
1998 return monotonic_clock::max_time;
1999 }
2000 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002001}
2002
2003void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002004 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002005 const aos::monotonic_clock::time_point end_queue_time =
2006 (sorted_messages_.size() > 0
2007 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002008 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002009 chrono::duration_cast<chrono::seconds>(
2010 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002011
2012 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002013 TimestampedMessage *m = timestamp_mapper_->Front();
2014 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002015 return;
2016 }
2017 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002018 // Stop placing sorted messages on the list once we have
2019 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2020 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002021 if (end_queue_time <
2022 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2023 return;
2024 }
2025 }
2026
Austin Schuh2f8fd752020-09-01 22:38:28 -07002027 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2028
Austin Schuh287d43d2020-12-04 20:19:33 -08002029 TimestampedMessage timestamped_message = std::move(*m);
2030 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002031
Austin Schuh2f8fd752020-09-01 22:38:28 -07002032 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002033 if (timestamped_message.monotonic_remote_time !=
2034 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002035 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002036 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002037
2038 CHECK(filter != nullptr);
2039
2040 // Call the correct method depending on if we are the forward or
2041 // reverse direction here.
2042 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002043 timestamped_message.monotonic_event_time,
2044 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002045 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002046 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002047 }
2048}
2049
2050void LogReader::State::Deregister() {
2051 for (size_t i = 0; i < channels_.size(); ++i) {
2052 channels_[i].reset();
2053 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002054 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002055 event_loop_unique_ptr_.reset();
2056 event_loop_ = nullptr;
2057 timer_handler_ = nullptr;
2058 node_event_loop_factory_ = nullptr;
2059}
2060
Austin Schuhe309d2a2019-11-29 13:25:21 -08002061} // namespace logger
2062} // namespace aos