blob: ef612c9b6d86a6c752897bff7ce9e277bbdec0fa [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 Schuh0de30f32020-12-06 12:44:28 -080018#include "aos/network/remote_message_generated.h"
19#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080020#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080021#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070022#include "aos/util/file.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080023#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070024#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080025
Austin Schuh15649d62019-12-28 16:36:38 -080026DEFINE_bool(skip_missing_forwarding_entries, false,
27 "If true, drop any forwarding entries with missing data. If "
28 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080029
Austin Schuh8bd96322020-02-13 21:18:22 -080030DEFINE_bool(timestamps_to_csv, false,
31 "If true, write all the time synchronization information to a set "
32 "of CSV files in /tmp/. This should only be needed when debugging "
33 "time synchronization.");
34
Austin Schuh2f8fd752020-09-01 22:38:28 -070035DEFINE_bool(skip_order_validation, false,
36 "If true, ignore any out of orderness in replay");
37
Austin Schuhf0688662020-12-19 15:37:45 -080038DEFINE_double(
39 time_estimation_buffer_seconds, 2.0,
40 "The time to buffer ahead in the log file to accurately reconstruct time.");
41
Austin Schuhe309d2a2019-11-29 13:25:21 -080042namespace aos {
43namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070044namespace {
45// Helper to safely read a header, or CHECK.
Austin Schuhadd6eb32020-11-09 21:24:26 -080046SizePrefixedFlatbufferVector<LogFileHeader> MaybeReadHeaderOrDie(
Austin Schuh287d43d2020-12-04 20:19:33 -080047 const std::vector<LogFile> &log_files) {
48 CHECK_GE(log_files.size(), 1u) << ": Empty filenames list";
49 CHECK_GE(log_files[0].parts.size(), 1u) << ": Empty filenames list";
50 CHECK_GE(log_files[0].parts[0].parts.size(), 1u) << ": Empty filenames list";
Austin Schuhadd6eb32020-11-09 21:24:26 -080051 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> result =
Austin Schuh287d43d2020-12-04 20:19:33 -080052 ReadHeader(log_files[0].parts[0].parts[0]);
Austin Schuh3bd4c402020-11-06 18:19:06 -080053 CHECK(result);
54 return result.value();
Austin Schuh0afc4d12020-10-19 11:42:04 -070055}
Austin Schuh0de30f32020-12-06 12:44:28 -080056
Austin Schuh315b96b2020-12-11 21:21:12 -080057std::string LogFileVectorToString(std::vector<LogFile> log_files) {
58 std::stringstream ss;
59 for (const auto f : log_files) {
60 ss << f << "\n";
61 }
62 return ss.str();
63}
64
Austin Schuh0de30f32020-12-06 12:44:28 -080065// Copies the channel, removing the schema as we go. If new_name is provided,
66// it is used instead of the name inside the channel. If new_type is provided,
67// it is used instead of the type in the channel.
68flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
69 std::string_view new_name,
70 std::string_view new_type,
71 flatbuffers::FlatBufferBuilder *fbb) {
72 flatbuffers::Offset<flatbuffers::String> name_offset =
73 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
74 : new_name);
75 flatbuffers::Offset<flatbuffers::String> type_offset =
76 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
77 flatbuffers::Offset<flatbuffers::String> source_node_offset =
78 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
79 : 0;
80
81 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
82 destination_nodes_offset =
83 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
84
85 flatbuffers::Offset<
86 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
87 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
88
89 Channel::Builder channel_builder(*fbb);
90 channel_builder.add_name(name_offset);
91 channel_builder.add_type(type_offset);
92 if (c->has_frequency()) {
93 channel_builder.add_frequency(c->frequency());
94 }
95 if (c->has_max_size()) {
96 channel_builder.add_max_size(c->max_size());
97 }
98 if (c->has_num_senders()) {
99 channel_builder.add_num_senders(c->num_senders());
100 }
101 if (c->has_num_watchers()) {
102 channel_builder.add_num_watchers(c->num_watchers());
103 }
104 if (!source_node_offset.IsNull()) {
105 channel_builder.add_source_node(source_node_offset);
106 }
107 if (!destination_nodes_offset.IsNull()) {
108 channel_builder.add_destination_nodes(destination_nodes_offset);
109 }
110 if (c->has_logger()) {
111 channel_builder.add_logger(c->logger());
112 }
113 if (!logger_nodes_offset.IsNull()) {
114 channel_builder.add_logger_nodes(logger_nodes_offset);
115 }
116 if (c->has_read_method()) {
117 channel_builder.add_read_method(c->read_method());
118 }
119 if (c->has_num_readers()) {
120 channel_builder.add_num_readers(c->num_readers());
121 }
122 return channel_builder.Finish();
123}
124
Austin Schuhe309d2a2019-11-29 13:25:21 -0800125namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800126using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700127} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800128
Brian Silverman1f345222020-09-24 21:14:48 -0700129Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
130 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800131 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700132 configuration_(configuration),
133 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700134 timer_handler_(event_loop_->AddTimer(
135 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700136 server_statistics_fetcher_(
137 configuration::MultiNode(event_loop_->configuration())
138 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
139 "/aos")
140 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700141 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700142
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700143 // Find all the nodes which are logging timestamps on our node. This may
144 // over-estimate if should_log is specified.
145 std::vector<const Node *> timestamp_logger_nodes =
146 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147
148 std::map<const Channel *, const Node *> timestamp_logger_channels;
149
150 // Now that we have all the nodes accumulated, make remote timestamp loggers
151 // for them.
152 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700153 // Note: since we are doing a find using the event loop channel, we need to
154 // make sure this channel pointer is part of the event loop configuration,
155 // not configuration_. This only matters when configuration_ !=
156 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700158 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800160 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700161 event_loop_->node());
162
163 CHECK(channel != nullptr)
164 << ": Remote timestamps are logged on "
165 << event_loop_->node()->name()->string_view()
166 << " but can't find channel /aos/remote_timestamps/"
167 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700168 if (!should_log(channel)) {
169 continue;
170 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700171 timestamp_logger_channels.insert(std::make_pair(channel, node));
172 }
173
Brian Silvermand90905f2020-09-23 14:42:56 -0700174 const size_t our_node_index =
175 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700176
Brian Silverman1f345222020-09-24 21:14:48 -0700177 for (size_t channel_index = 0;
178 channel_index < configuration_->channels()->size(); ++channel_index) {
179 const Channel *const config_channel =
180 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700181 // The MakeRawFetcher method needs a channel which is in the event loop
182 // configuration() object, not the configuration_ object. Go look that up
183 // from the config.
184 const Channel *channel = aos::configuration::GetChannel(
185 event_loop_->configuration(), config_channel->name()->string_view(),
186 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700187 CHECK(channel != nullptr)
188 << ": Failed to look up channel "
189 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700190 if (!should_log(channel)) {
191 continue;
192 }
Austin Schuh0c297012020-09-16 18:41:59 -0700193
Austin Schuhe309d2a2019-11-29 13:25:21 -0800194 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700195 fs.channel_index = channel_index;
196 fs.channel = channel;
197
Austin Schuh6f3babe2020-01-26 20:34:50 -0800198 const bool is_local =
199 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
200
Austin Schuh15649d62019-12-28 16:36:38 -0800201 const bool is_readable =
202 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700203 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
204 channel, event_loop_->node());
205 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800206
Brian Silverman1f345222020-09-24 21:14:48 -0700207 bool log_delivery_times = false;
208 if (event_loop_->node() != nullptr) {
209 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
210 channel, event_loop_->node(), event_loop_->node());
211 }
Austin Schuh15649d62019-12-28 16:36:38 -0800212
Austin Schuh0de30f32020-12-06 12:44:28 -0800213 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700214 // contents to a file directly.
215 const bool log_contents = timestamp_logger_channels.find(channel) !=
216 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700217
218 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800219 fs.fetcher = event_loop->MakeRawFetcher(channel);
220 VLOG(1) << "Logging channel "
221 << configuration::CleanedChannelToString(channel);
222
223 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700225 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800226 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800227 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800228 if (log_message) {
229 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700230 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800231 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800232 const Node *source_node = configuration::GetNode(
233 configuration_, channel->source_node()->string_view());
234 fs.data_node_index =
235 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800237 } else {
238 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800239 }
240 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700241 if (log_contents) {
242 VLOG(1) << "Timestamp logger channel "
243 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700244 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
245 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800246 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700247 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700248 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800249 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800250 }
Brian Silverman1f345222020-09-24 21:14:48 -0700251 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700252
253 // When we are logging remote timestamps, we need to be able to translate from
254 // the channel index that the event loop uses to the channel index in the
255 // config in the log file.
256 event_loop_to_logged_channel_index_.resize(
257 event_loop->configuration()->channels()->size(), -1);
258 for (size_t event_loop_channel_index = 0;
259 event_loop_channel_index <
260 event_loop->configuration()->channels()->size();
261 ++event_loop_channel_index) {
262 const Channel *event_loop_channel =
263 event_loop->configuration()->channels()->Get(event_loop_channel_index);
264
265 const Channel *logged_channel = aos::configuration::GetChannel(
266 configuration_, event_loop_channel->name()->string_view(),
267 event_loop_channel->type()->string_view(), "",
268 configuration::GetNode(configuration_, event_loop_->node()));
269
270 if (logged_channel != nullptr) {
271 event_loop_to_logged_channel_index_[event_loop_channel_index] =
272 configuration::ChannelIndex(configuration_, logged_channel);
273 }
274 }
Brian Silverman1f345222020-09-24 21:14:48 -0700275}
276
277Logger::~Logger() {
278 if (log_namer_) {
279 // If we are replaying a log file, or in simulation, we want to force the
280 // last bit of data to be logged. The easiest way to deal with this is to
281 // poll everything as we go to destroy the class, ie, shut down the logger,
282 // and write it to disk.
283 StopLogging(event_loop_->monotonic_now());
284 }
285}
286
Brian Silvermanae7c0332020-09-30 16:58:23 -0700287void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
288 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700289 CHECK(!log_namer_) << ": Already logging";
290 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700291 log_event_uuid_ = UUID::Random();
292 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700293 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
294
295 // We want to do as much work as possible before the initial Fetch. Time
296 // between that and actually starting to log opens up the possibility of
297 // falling off the end of the queue during that time.
298
299 for (FetcherStruct &f : fetchers_) {
300 if (f.wants_writer) {
301 f.writer = log_namer_->MakeWriter(f.channel);
302 }
303 if (f.wants_timestamp_writer) {
304 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
305 }
306 if (f.wants_contents_writer) {
307 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
308 f.channel, CHECK_NOTNULL(f.timestamp_node));
309 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800310 }
311
Brian Silverman1f345222020-09-24 21:14:48 -0700312 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700313 node_state_.resize(configuration::MultiNode(configuration_)
314 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700315 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800316
Austin Schuh2f8fd752020-09-01 22:38:28 -0700317 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700318 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800319
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 node_state_[node_index].log_file_header = MakeHeader(node);
321 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800322
Austin Schuh2f8fd752020-09-01 22:38:28 -0700323 // Grab data from each channel right before we declare the log file started
324 // so we can capture the latest message on each channel. This lets us have
325 // non periodic messages with configuration that now get logged.
326 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700327 const auto start = event_loop_->monotonic_now();
328 const bool got_new = f.fetcher->Fetch();
329 const auto end = event_loop_->monotonic_now();
330 RecordFetchResult(start, end, got_new, &f);
331
332 // If there is a message, we want to write it.
333 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700334 }
335
336 // Clear out any old timestamps in case we are re-starting logging.
337 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800338 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
339 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700340 }
341
342 WriteHeader();
343
344 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
345 << " start_time " << last_synchronized_time_;
346
Austin Schuh315b96b2020-12-11 21:21:12 -0800347 // Force logging up until the start of the log file now, so the messages at
348 // the start are always ordered before the rest of the messages.
349 // Note: this ship may have already sailed, but we don't have to make it
350 // worse.
351 // TODO(austin): Test...
352 LogUntil(last_synchronized_time_);
353
Austin Schuh2f8fd752020-09-01 22:38:28 -0700354 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
355 polling_period_);
356}
357
Brian Silverman1f345222020-09-24 21:14:48 -0700358std::unique_ptr<LogNamer> Logger::StopLogging(
359 aos::monotonic_clock::time_point end_time) {
360 CHECK(log_namer_) << ": Not logging right now";
361
362 if (end_time != aos::monotonic_clock::min_time) {
363 LogUntil(end_time);
364 }
365 timer_handler_->Disable();
366
367 for (FetcherStruct &f : fetchers_) {
368 f.writer = nullptr;
369 f.timestamp_writer = nullptr;
370 f.contents_writer = nullptr;
371 }
372 node_state_.clear();
373
Brian Silvermanae7c0332020-09-30 16:58:23 -0700374 log_event_uuid_ = UUID::Zero();
375 log_start_uuid_ = std::string();
376
Brian Silverman1f345222020-09-24 21:14:48 -0700377 return std::move(log_namer_);
378}
379
Austin Schuhfa895892020-01-07 20:07:41 -0800380void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700381 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700382 server_statistics_fetcher_.Fetch();
383 }
384
385 aos::monotonic_clock::time_point monotonic_start_time =
386 event_loop_->monotonic_now();
387 aos::realtime_clock::time_point realtime_start_time =
388 event_loop_->realtime_now();
389
390 // We need to pick a point in time to declare the log file "started". This
391 // starts here. It needs to be after everything is fetched so that the
392 // fetchers are all pointed at the most recent message before the start
393 // time.
394 last_synchronized_time_ = monotonic_start_time;
395
Austin Schuh6f3babe2020-01-26 20:34:50 -0800396 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700397 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700398 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
399 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800400 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800401 }
402}
Austin Schuh8bd96322020-02-13 21:18:22 -0800403
Austin Schuh315b96b2020-12-11 21:21:12 -0800404void Logger::MaybeWriteHeader(int node_index) {
405 if (configuration::MultiNode(configuration_)) {
406 return MaybeWriteHeader(node_index,
407 configuration_->nodes()->Get(node_index));
408 } else {
409 return MaybeWriteHeader(node_index, nullptr);
410 }
411}
412
413void Logger::MaybeWriteHeader(int node_index, const Node *node) {
414 // This function is responsible for writing the header when the header both
415 // has valid data, and when it needs to be written.
416 if (node_state_[node_index].header_written &&
417 node_state_[node_index].header_valid) {
418 // The header has been written and is valid, nothing to do.
419 return;
420 }
421 if (!node_state_[node_index].has_source_node_boot_uuid) {
422 // Can't write a header if we don't have the boot UUID.
423 return;
424 }
425
426 // WriteHeader writes the first header in a log file. We want to do this only
427 // once.
428 //
429 // Rotate rewrites the same header with a new part ID, but keeps the same part
430 // UUID. We don't want that when things reboot, because that implies that
431 // parts go together across a reboot.
432 //
433 // Reboot resets the parts UUID. So, once we've written a header the first
434 // time, we want to use Reboot to rotate the log and reset the parts UUID.
435 //
436 // header_valid is cleared whenever the remote reboots.
437 if (node_state_[node_index].header_written) {
438 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
439 } else {
440 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
441
442 node_state_[node_index].header_written = true;
443 }
444 node_state_[node_index].header_valid = true;
445}
446
Austin Schuh2f8fd752020-09-01 22:38:28 -0700447void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700448 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700449 server_statistics_fetcher_.Fetch();
450 } else {
451 return;
452 }
453
454 if (server_statistics_fetcher_.get() == nullptr) {
455 return;
456 }
457
458 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700459 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700460 if (MaybeUpdateTimestamp(
461 node, node_index,
462 server_statistics_fetcher_.context().monotonic_event_time,
463 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800464 CHECK(node_state_[node_index].header_written);
465 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700466 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800467 } else {
468 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700469 }
470 }
471}
472
Austin Schuh315b96b2020-12-11 21:21:12 -0800473void Logger::SetStartTime(
474 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
475 aos::realtime_clock::time_point realtime_start_time,
476 aos::monotonic_clock::time_point logger_monotonic_start_time,
477 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700478 node_state_[node_index].monotonic_start_time = monotonic_start_time;
479 node_state_[node_index].realtime_start_time = realtime_start_time;
480 node_state_[node_index]
481 .log_file_header.mutable_message()
482 ->mutate_monotonic_start_time(
483 std::chrono::duration_cast<std::chrono::nanoseconds>(
484 monotonic_start_time.time_since_epoch())
485 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800486
487 // Add logger start times if they are available in the log file header.
488 if (node_state_[node_index]
489 .log_file_header.mutable_message()
490 ->has_logger_monotonic_start_time()) {
491 node_state_[node_index]
492 .log_file_header.mutable_message()
493 ->mutate_logger_monotonic_start_time(
494 std::chrono::duration_cast<std::chrono::nanoseconds>(
495 logger_monotonic_start_time.time_since_epoch())
496 .count());
497 }
498
499 if (node_state_[node_index]
500 .log_file_header.mutable_message()
501 ->has_logger_realtime_start_time()) {
502 node_state_[node_index]
503 .log_file_header.mutable_message()
504 ->mutate_logger_realtime_start_time(
505 std::chrono::duration_cast<std::chrono::nanoseconds>(
506 logger_realtime_start_time.time_since_epoch())
507 .count());
508 }
509
Austin Schuh2f8fd752020-09-01 22:38:28 -0700510 if (node_state_[node_index]
511 .log_file_header.mutable_message()
512 ->has_realtime_start_time()) {
513 node_state_[node_index]
514 .log_file_header.mutable_message()
515 ->mutate_realtime_start_time(
516 std::chrono::duration_cast<std::chrono::nanoseconds>(
517 realtime_start_time.time_since_epoch())
518 .count());
519 }
520}
521
522bool Logger::MaybeUpdateTimestamp(
523 const Node *node, int node_index,
524 aos::monotonic_clock::time_point monotonic_start_time,
525 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700526 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700527 if (node_state_[node_index].monotonic_start_time !=
528 monotonic_clock::min_time) {
529 return false;
530 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800531 if (event_loop_->node() == node ||
532 !configuration::MultiNode(configuration_)) {
533 // There are no offsets to compute for ourself, so always succeed.
534 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
535 monotonic_start_time, realtime_start_time);
536 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700537 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800538 } else if (server_statistics_fetcher_.get() != nullptr) {
539 // We must be a remote node now. Look for the connection and see if it is
540 // connected.
541
542 for (const message_bridge::ServerConnection *connection :
543 *server_statistics_fetcher_->connections()) {
544 if (connection->node()->name()->string_view() !=
545 node->name()->string_view()) {
546 continue;
547 }
548
549 if (connection->state() != message_bridge::State::CONNECTED) {
550 VLOG(1) << node->name()->string_view()
551 << " is not connected, can't start it yet.";
552 break;
553 }
554
555 // Update the boot UUID as soon as we know we are connected.
556 if (!connection->has_boot_uuid()) {
557 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
558 break;
559 }
560
561 if (!node_state_[node_index].has_source_node_boot_uuid ||
562 node_state_[node_index].source_node_boot_uuid !=
563 connection->boot_uuid()->string_view()) {
564 node_state_[node_index].SetBootUUID(
565 connection->boot_uuid()->string_view());
566 }
567
568 if (!connection->has_monotonic_offset()) {
569 VLOG(1) << "Missing monotonic offset for setting start time for node "
570 << aos::FlatbufferToJson(node);
571 break;
572 }
573
574 // Found it and it is connected. Compensate and go.
575 SetStartTime(node_index,
576 monotonic_start_time +
577 std::chrono::nanoseconds(connection->monotonic_offset()),
578 realtime_start_time, monotonic_start_time,
579 realtime_start_time);
580 return true;
581 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700582 }
583 return false;
584}
585
586aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
587 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800588 // Now write the header with this timestamp in it.
589 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800590 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800591
Austin Schuh2f8fd752020-09-01 22:38:28 -0700592 // TODO(austin): Compress this much more efficiently. There are a bunch of
593 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700594 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700595 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800596
Brian Silvermanae7c0332020-09-30 16:58:23 -0700597 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700598 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800599
Brian Silvermanae7c0332020-09-30 16:58:23 -0700600 CHECK(log_event_uuid_ != UUID::Zero());
601 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
602 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700603
Brian Silvermanae7c0332020-09-30 16:58:23 -0700604 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
605 fbb.CreateString(logger_instance_uuid_.string_view());
606
607 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
608 if (!log_start_uuid_.empty()) {
609 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
610 }
611
Austin Schuh315b96b2020-12-11 21:21:12 -0800612 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
613 fbb.CreateString(event_loop_->boot_uuid().string_view());
614
615 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
616 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700617
618 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700619 fbb.CreateString("00000000-0000-4000-8000-000000000000");
620
Austin Schuhfa895892020-01-07 20:07:41 -0800621 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700622 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700623
Austin Schuh0c297012020-09-16 18:41:59 -0700624 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800625 // TODO(austin): Reuse the node we just copied in above.
626 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
627 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800628 }
629
630 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
631
Austin Schuh64fab802020-09-09 22:47:47 -0700632 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800633
634 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800635 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800636 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700637 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800638 }
639
640 log_file_header_builder.add_configuration(configuration_offset);
641 // The worst case theoretical out of order is the polling period times 2.
642 // One message could get logged right after the boundary, but be for right
643 // before the next boundary. And the reverse could happen for another
644 // message. Report back 3x to be extra safe, and because the cost isn't
645 // huge on the read side.
646 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700647 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800648
649 log_file_header_builder.add_monotonic_start_time(
650 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700651 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800652 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700653 if (node == event_loop_->node()) {
654 log_file_header_builder.add_realtime_start_time(
655 std::chrono::duration_cast<std::chrono::nanoseconds>(
656 realtime_clock::min_time.time_since_epoch())
657 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800658 } else {
659 log_file_header_builder.add_logger_monotonic_start_time(
660 std::chrono::duration_cast<std::chrono::nanoseconds>(
661 monotonic_clock::min_time.time_since_epoch())
662 .count());
663 log_file_header_builder.add_logger_realtime_start_time(
664 std::chrono::duration_cast<std::chrono::nanoseconds>(
665 realtime_clock::min_time.time_since_epoch())
666 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800667 }
668
Brian Silvermanae7c0332020-09-30 16:58:23 -0700669 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
670 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
671 if (!log_start_uuid_offset.IsNull()) {
672 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
673 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800674 log_file_header_builder.add_logger_node_boot_uuid(
675 logger_node_boot_uuid_offset);
676 log_file_header_builder.add_source_node_boot_uuid(
677 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700678
679 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
680 log_file_header_builder.add_parts_index(0);
681
Austin Schuh2f8fd752020-09-01 22:38:28 -0700682 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800683 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
684 fbb.Release());
685
686 CHECK(result.Verify()) << ": Built a corrupted header.";
687
688 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700689}
690
Brian Silvermancb805822020-10-06 17:43:35 -0700691void Logger::ResetStatisics() {
692 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
693 max_message_fetch_time_channel_ = -1;
694 max_message_fetch_time_size_ = -1;
695 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
696 total_message_fetch_count_ = 0;
697 total_message_fetch_bytes_ = 0;
698 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
699 total_nop_fetch_count_ = 0;
700 max_copy_time_ = std::chrono::nanoseconds::zero();
701 max_copy_time_channel_ = -1;
702 max_copy_time_size_ = -1;
703 total_copy_time_ = std::chrono::nanoseconds::zero();
704 total_copy_count_ = 0;
705 total_copy_bytes_ = 0;
706}
707
Austin Schuh2f8fd752020-09-01 22:38:28 -0700708void Logger::Rotate() {
709 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700710 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700711 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700712 }
713}
714
715void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800716 // Grab the latest ServerStatistics message. This will always have the
717 // oppertunity to be >= to the current time, so it will always represent any
718 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700719 WriteMissingTimestamps();
720
721 // Write each channel to disk, one at a time.
722 for (FetcherStruct &f : fetchers_) {
723 while (true) {
724 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700725 const auto start = event_loop_->monotonic_now();
726 const bool got_new = f.fetcher->FetchNext();
727 const auto end = event_loop_->monotonic_now();
728 RecordFetchResult(start, end, got_new, &f);
729 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700730 VLOG(2) << "No new data on "
731 << configuration::CleanedChannelToString(
732 f.fetcher->channel());
733 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700734 }
Brian Silvermancb805822020-10-06 17:43:35 -0700735 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 }
737
Austin Schuh2f8fd752020-09-01 22:38:28 -0700738 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700739 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700740 break;
741 }
Brian Silvermancb805822020-10-06 17:43:35 -0700742 if (f.writer != nullptr) {
743 // Write!
744 const auto start = event_loop_->monotonic_now();
745 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
746 max_header_size_);
747 fbb.ForceDefaults(true);
748
749 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
750 f.channel_index, f.log_type));
751 const auto end = event_loop_->monotonic_now();
752 RecordCreateMessageTime(start, end, &f);
753
754 VLOG(2) << "Writing data as node "
755 << FlatbufferToJson(event_loop_->node()) << " for channel "
756 << configuration::CleanedChannelToString(f.fetcher->channel())
757 << " to " << f.writer->filename() << " data "
758 << FlatbufferToJson(
759 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
760 fbb.GetBufferPointer()));
761
762 max_header_size_ = std::max(max_header_size_,
763 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800764 CHECK(node_state_[f.data_node_index].header_valid)
765 << ": Can't write data before the header on channel "
766 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700767 f.writer->QueueSizedFlatbuffer(&fbb);
768 }
769
770 if (f.timestamp_writer != nullptr) {
771 // And now handle timestamps.
772 const auto start = event_loop_->monotonic_now();
773 flatbuffers::FlatBufferBuilder fbb;
774 fbb.ForceDefaults(true);
775
776 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
777 f.channel_index,
778 LogType::kLogDeliveryTimeOnly));
779 const auto end = event_loop_->monotonic_now();
780 RecordCreateMessageTime(start, end, &f);
781
782 VLOG(2) << "Writing timestamps as node "
783 << FlatbufferToJson(event_loop_->node()) << " for channel "
784 << configuration::CleanedChannelToString(f.fetcher->channel())
785 << " to " << f.timestamp_writer->filename() << " timestamp "
786 << FlatbufferToJson(
787 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
788 fbb.GetBufferPointer()));
789
Austin Schuh315b96b2020-12-11 21:21:12 -0800790 CHECK(node_state_[f.timestamp_node_index].header_valid)
791 << ": Can't write data before the header on channel "
792 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700793 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
794 }
795
796 if (f.contents_writer != nullptr) {
797 const auto start = event_loop_->monotonic_now();
798 // And now handle the special message contents channel. Copy the
799 // message into a FlatBufferBuilder and save it to disk.
800 // TODO(austin): We can be more efficient here when we start to
801 // care...
802 flatbuffers::FlatBufferBuilder fbb;
803 fbb.ForceDefaults(true);
804
Austin Schuh0de30f32020-12-06 12:44:28 -0800805 const RemoteMessage *msg =
806 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700807
Austin Schuh315b96b2020-12-11 21:21:12 -0800808 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
809 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
810 node_state_[f.contents_node_index].source_node_boot_uuid !=
811 msg->boot_uuid()->string_view()) {
812 node_state_[f.contents_node_index].SetBootUUID(
813 msg->boot_uuid()->string_view());
814
815 MaybeWriteHeader(f.contents_node_index);
816 }
817
Brian Silvermancb805822020-10-06 17:43:35 -0700818 logger::MessageHeader::Builder message_header_builder(fbb);
819
820 // TODO(austin): This needs to check the channel_index and confirm
821 // that it should be logged before squirreling away the timestamp to
822 // disk. We don't want to log irrelevant timestamps.
823
824 // Note: this must match the same order as MessageBridgeServer and
825 // PackMessage. We want identical headers to have identical
826 // on-the-wire formats to make comparing them easier.
827
828 // Translate from the channel index that the event loop uses to the
829 // channel index in the log file.
830 message_header_builder.add_channel_index(
831 event_loop_to_logged_channel_index_[msg->channel_index()]);
832
833 message_header_builder.add_queue_index(msg->queue_index());
834 message_header_builder.add_monotonic_sent_time(
835 msg->monotonic_sent_time());
836 message_header_builder.add_realtime_sent_time(
837 msg->realtime_sent_time());
838
839 message_header_builder.add_monotonic_remote_time(
840 msg->monotonic_remote_time());
841 message_header_builder.add_realtime_remote_time(
842 msg->realtime_remote_time());
843 message_header_builder.add_remote_queue_index(
844 msg->remote_queue_index());
845
846 fbb.FinishSizePrefixed(message_header_builder.Finish());
847 const auto end = event_loop_->monotonic_now();
848 RecordCreateMessageTime(start, end, &f);
849
Austin Schuh315b96b2020-12-11 21:21:12 -0800850 CHECK(node_state_[f.contents_node_index].header_valid)
851 << ": Can't write data before the header on channel "
852 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700853 f.contents_writer->QueueSizedFlatbuffer(&fbb);
854 }
855
856 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700857 }
858 }
859 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800860}
861
Brian Silverman1f345222020-09-24 21:14:48 -0700862void Logger::DoLogData(const monotonic_clock::time_point end_time) {
863 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800864 // max_out_of_order_duration. To do this, we need sync points. Every write
865 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800866
867 do {
868 // Move the sync point up by at most polling_period. This forces one sync
869 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700870 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
871
872 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800873
Austin Schuhe309d2a2019-11-29 13:25:21 -0800874 // If we missed cycles, we could be pretty far behind. Spin until we are
875 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700876 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800877}
878
Brian Silvermancb805822020-10-06 17:43:35 -0700879void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
880 aos::monotonic_clock::time_point end,
881 bool got_new, FetcherStruct *fetcher) {
882 const auto duration = end - start;
883 if (!got_new) {
884 ++total_nop_fetch_count_;
885 total_nop_fetch_time_ += duration;
886 return;
887 }
888 ++total_message_fetch_count_;
889 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
890 total_message_fetch_time_ += duration;
891 if (duration > max_message_fetch_time_) {
892 max_message_fetch_time_ = duration;
893 max_message_fetch_time_channel_ = fetcher->channel_index;
894 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
895 }
896}
897
898void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
899 aos::monotonic_clock::time_point end,
900 FetcherStruct *fetcher) {
901 const auto duration = end - start;
902 total_copy_time_ += duration;
903 ++total_copy_count_;
904 total_copy_bytes_ += fetcher->fetcher->context().size;
905 if (duration > max_copy_time_) {
906 max_copy_time_ = duration;
907 max_copy_time_channel_ = fetcher->channel_index;
908 max_copy_time_size_ = fetcher->fetcher->context().size;
909 }
910}
911
Austin Schuh11d43732020-09-21 17:28:30 -0700912std::vector<std::vector<std::string>> ToLogReaderVector(
913 const std::vector<LogFile> &log_files) {
914 std::vector<std::vector<std::string>> result;
915 for (const LogFile &log_file : log_files) {
916 for (const LogParts &log_parts : log_file.parts) {
917 std::vector<std::string> parts;
918 for (const std::string &part : log_parts.parts) {
919 parts.emplace_back(part);
920 }
921 result.emplace_back(std::move(parts));
922 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700923 }
924 return result;
925}
926
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800927LogReader::LogReader(std::string_view filename,
928 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800929 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800930
Austin Schuh287d43d2020-12-04 20:19:33 -0800931LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800932 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800933 : log_files_(std::move(log_files)),
934 log_file_header_(MaybeReadHeaderOrDie(log_files_)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800935 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800936 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800937
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700938 // Remap all existing remote timestamp channels. They will be recreated, and
939 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700940 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700941 std::vector<const Node *> timestamp_logger_nodes =
942 configuration::TimestampNodes(logged_configuration(), node);
943 for (const Node *remote_node : timestamp_logger_nodes) {
944 const std::string channel = absl::StrCat(
945 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800946 // See if the log file is an old log with MessageHeader channels in it, or
947 // a newer log with RemoteMessage. If we find an older log, rename the
948 // type too along with the name.
949 if (HasChannel<MessageHeader>(channel, node)) {
950 CHECK(!HasChannel<RemoteMessage>(channel, node))
951 << ": Can't have both a MessageHeader and RemoteMessage remote "
952 "timestamp channel.";
953 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
954 "aos.message_bridge.RemoteMessage");
955 } else {
956 CHECK(HasChannel<RemoteMessage>(channel, node))
957 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
958 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
959 << node->name()->string_view();
960 RemapLoggedChannel<RemoteMessage>(channel, node);
961 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700962 }
963 }
964
Austin Schuh6aa77be2020-02-22 21:06:40 -0800965 if (replay_configuration) {
966 CHECK_EQ(configuration::MultiNode(configuration()),
967 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700968 << ": Log file and replay config need to both be multi or single "
969 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800970 }
971
Austin Schuh6f3babe2020-01-26 20:34:50 -0800972 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800973 states_.emplace_back(std::make_unique<State>(
974 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800975 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800976 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700977 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800978 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700979 << ": Log file and replay config need to have matching nodes "
980 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700981 for (const Node *node : *logged_configuration()->nodes()) {
982 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700983 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
984 << " in logged config that is not present in the replay "
985 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700986 }
987 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800988 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800989 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800990 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800991}
992
Austin Schuh6aa77be2020-02-22 21:06:40 -0800993LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700994 if (event_loop_factory_unique_ptr_) {
995 Deregister();
996 } else if (event_loop_factory_ != nullptr) {
997 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
998 "is destroyed";
999 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001000 if (offset_fp_ != nullptr) {
1001 fclose(offset_fp_);
1002 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001003 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1004 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001005 if (remapped_configuration_buffer_) {
1006 remapped_configuration_buffer_->Wipe();
1007 }
1008 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -08001009}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001010
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001011const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001012 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001013}
1014
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001015const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001016 return remapped_configuration_;
1017}
1018
Austin Schuh6f3babe2020-01-26 20:34:50 -08001019std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001020 // Because the Node pointer will only be valid if it actually points to
1021 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001022 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001023 //
1024 // Also, note, that when ever a map is changed, the nodes in here are
1025 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001026 CHECK(remapped_configuration_ != nullptr)
1027 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001028 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001029}
Austin Schuh15649d62019-12-28 16:36:38 -08001030
Austin Schuh11d43732020-09-21 17:28:30 -07001031monotonic_clock::time_point LogReader::monotonic_start_time(
1032 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001033 State *state =
1034 states_[configuration::GetNodeIndex(configuration(), node)].get();
1035 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1036
Austin Schuh858c9f32020-08-31 16:56:12 -07001037 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001038}
1039
Austin Schuh11d43732020-09-21 17:28:30 -07001040realtime_clock::time_point LogReader::realtime_start_time(
1041 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001042 State *state =
1043 states_[configuration::GetNodeIndex(configuration(), node)].get();
1044 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1045
Austin Schuh858c9f32020-08-31 16:56:12 -07001046 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001047}
1048
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001049void LogReader::Register() {
1050 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001051 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001052 Register(event_loop_factory_unique_ptr_.get());
1053}
1054
Austin Schuh92547522019-12-28 14:33:43 -08001055void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001056 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001057 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -08001058
Brian Silvermand90905f2020-09-23 14:42:56 -07001059 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001060 const size_t node_index =
1061 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001062 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1063 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001064
1065 // Confirm that all the parts are from the same boot if there are enough
1066 // parts to not be from the same boot.
1067 if (filtered_parts.size() > 1u) {
1068 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1069 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1070 filtered_parts[0].source_boot_uuid)
1071 << ": Found parts from different boots "
1072 << LogFileVectorToString(log_files_);
1073 }
1074 }
1075
Austin Schuh287d43d2020-12-04 20:19:33 -08001076 states_[node_index] = std::make_unique<State>(
1077 filtered_parts.size() == 0u
1078 ? nullptr
1079 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001080 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001081 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001082 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001083
1084 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001085 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001086
Austin Schuh287d43d2020-12-04 20:19:33 -08001087 for (const Node *node : configuration::GetNodes(configuration())) {
1088 const size_t node_index =
1089 configuration::GetNodeIndex(configuration(), node);
1090 State *state = states_[node_index].get();
1091 for (const Node *other_node : configuration::GetNodes(configuration())) {
1092 const size_t other_node_index =
1093 configuration::GetNodeIndex(configuration(), other_node);
1094 State *other_state = states_[other_node_index].get();
1095 if (other_state != state) {
1096 state->AddPeer(other_state);
1097 }
1098 }
1099 }
1100
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001101 // Register after making all the State objects so we can build references
1102 // between them.
1103 for (const Node *node : configuration::GetNodes(configuration())) {
1104 const size_t node_index =
1105 configuration::GetNodeIndex(configuration(), node);
1106 State *state = states_[node_index].get();
1107
1108 Register(state->event_loop());
1109 }
1110
James Kuszmaul46d82582020-05-09 19:50:09 -07001111 if (live_nodes_ == 0) {
1112 LOG(FATAL)
1113 << "Don't have logs from any of the nodes in the replay config--are "
1114 "you sure that the replay config matches the original config?";
1115 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001116
Austin Schuh2f8fd752020-09-01 22:38:28 -07001117 // We need to now seed our per-node time offsets and get everything set up
1118 // to run.
1119 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -08001120
Austin Schuh8bd96322020-02-13 21:18:22 -08001121 // It is easiest to solve for per node offsets with a matrix rather than
1122 // trying to solve the equations by hand. So let's get after it.
1123 //
1124 // Now, build up the map matrix.
1125 //
Austin Schuh2f8fd752020-09-01 22:38:28 -07001126 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
1127 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1128 filters_.size() + 1, num_nodes);
1129 slope_matrix_ =
1130 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1131 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -08001132
Austin Schuh2f8fd752020-09-01 22:38:28 -07001133 offset_matrix_ =
1134 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1135 valid_matrix_ =
1136 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1137 last_valid_matrix_ =
1138 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -08001139
Austin Schuh2f8fd752020-09-01 22:38:28 -07001140 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
1141 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -08001142
Austin Schuh2f8fd752020-09-01 22:38:28 -07001143 // All times should average out to the distributed clock.
1144 for (int i = 0; i < map_matrix_.cols(); ++i) {
1145 // 1/num_nodes.
1146 map_matrix_(0, i) = mpq_class(1, num_nodes);
1147 }
1148 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -08001149
1150 {
1151 // Now, add the a - b -> sample elements.
1152 size_t i = 1;
1153 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001154 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1155 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001156 const Node *const node_a = std::get<0>(filter.first);
1157 const Node *const node_b = std::get<1>(filter.first);
1158
1159 const size_t node_a_index =
1160 configuration::GetNodeIndex(configuration(), node_a);
1161 const size_t node_b_index =
1162 configuration::GetNodeIndex(configuration(), node_b);
1163
Austin Schuh2f8fd752020-09-01 22:38:28 -07001164 // -a
1165 map_matrix_(i, node_a_index) = mpq_class(-1);
1166 // +b
1167 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -08001168
1169 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -07001170 std::get<0>(filter.second)
1171 .set_slope_pointer(&slope_matrix_(i, node_a_index));
1172 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
1173
1174 valid_matrix_(i) = false;
1175 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -08001176
1177 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001178 }
1179 }
1180
Austin Schuh858c9f32020-08-31 16:56:12 -07001181 for (std::unique_ptr<State> &state : states_) {
1182 state->SeedSortedMessages();
1183 }
1184
Austin Schuh2f8fd752020-09-01 22:38:28 -07001185 // Rank of the map matrix tells you if all the nodes are in communication
1186 // with each other, which tells you if the offsets are observable.
1187 const size_t connected_nodes =
1188 Eigen::FullPivLU<
1189 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
1190 .rank();
1191
1192 // We don't need to support isolated nodes until someone has a real use
1193 // case.
1194 CHECK_EQ(connected_nodes, num_nodes)
1195 << ": There is a node which isn't communicating with the rest.";
1196
1197 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001198 UpdateOffsets();
1199
Austin Schuh2f8fd752020-09-01 22:38:28 -07001200 // We want to start the log file at the last start time of the log files
1201 // from all the nodes. Compute how long each node's simulation needs to run
1202 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001203 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001204
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205 // TODO(austin): We want an "OnStart" callback for each node rather than
1206 // running until the last node.
1207
Austin Schuh8bd96322020-02-13 21:18:22 -08001208 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001209 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1210 << MaybeNodeName(state->event_loop()->node()) << "now "
1211 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001212 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1213 continue;
1214 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001215 // And start computing the start time on the distributed clock now that
1216 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001217 start_time = std::max(
1218 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001219 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001220
1221 CHECK_GE(start_time, distributed_clock::epoch())
1222 << ": Hmm, we have a node starting before the start of time. Offset "
1223 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001224
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1226 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001227 // nodes, and also replayed on the other nodes. This may not satisfy all
1228 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001229 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1230 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1231 const Channel *channel = logged_configuration()->channels()->Get(i);
1232 const Node *node = configuration::GetNode(
1233 configuration(), channel->source_node()->string_view());
1234
Austin Schuh8bd96322020-02-13 21:18:22 -08001235 State *state =
1236 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001237
1238 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001239 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001240
1241 event_loop_factory_->DisableForwarding(remapped_channel);
1242 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001243
1244 // If we are replaying a log, we don't want a bunch of redundant messages
1245 // from both the real message bridge and simulated message bridge.
1246 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001247 }
1248
Austin Schuhcde938c2020-02-02 17:30:07 -08001249 // While we are starting the system up, we might be relying on matching data
1250 // to timestamps on log files where the timestamp log file starts before the
1251 // data. In this case, it is reasonable to expect missing data.
1252 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001253 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001254 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001255 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001256 // Now that we are running for real, missing data means that the log file is
1257 // corrupted or went wrong.
1258 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001259
Austin Schuh8bd96322020-02-13 21:18:22 -08001260 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001261 // Make the RT clock be correct before handing it to the user.
1262 if (state->realtime_start_time() != realtime_clock::min_time) {
1263 state->SetRealtimeOffset(state->monotonic_start_time(),
1264 state->realtime_start_time());
1265 }
1266 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1267 << MaybeNodeName(state->event_loop()->node()) << "now "
1268 << state->monotonic_now();
1269 }
1270
1271 if (FLAGS_timestamps_to_csv) {
1272 for (std::pair<const std::tuple<const Node *, const Node *>,
1273 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1274 &filter : filters_) {
1275 const Node *const node_a = std::get<0>(filter.first);
1276 const Node *const node_b = std::get<1>(filter.first);
1277
1278 std::get<0>(filter.second)
1279 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1280 ->monotonic_now());
1281 std::get<0>(filter.second)
1282 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1283 ->monotonic_now());
1284 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001285 }
1286}
1287
Austin Schuh2f8fd752020-09-01 22:38:28 -07001288void LogReader::UpdateOffsets() {
1289 VLOG(2) << "Samples are " << offset_matrix_;
1290 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1291 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1292 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1293 "]");
1294 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1295 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1296
1297 size_t node_index = 0;
1298 for (std::unique_ptr<State> &state : states_) {
1299 state->SetDistributedOffset(offset(node_index), slope(node_index));
1300 VLOG(1) << "Offset for node " << node_index << " "
1301 << MaybeNodeName(state->event_loop()->node()) << "is "
1302 << aos::distributed_clock::time_point(offset(node_index))
1303 << " slope " << std::setprecision(9) << std::fixed
1304 << slope(node_index);
1305 ++node_index;
1306 }
1307
1308 if (VLOG_IS_ON(1)) {
1309 LogFit("Offset is");
1310 }
1311}
1312
1313void LogReader::LogFit(std::string_view prefix) {
1314 for (std::unique_ptr<State> &state : states_) {
1315 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1316 << state->monotonic_now() << " distributed "
1317 << event_loop_factory_->distributed_now();
1318 }
1319
1320 for (std::pair<const std::tuple<const Node *, const Node *>,
1321 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1322 filters_) {
1323 message_bridge::NoncausalOffsetEstimator *estimator =
1324 &std::get<0>(filter.second);
1325
1326 if (estimator->a_timestamps().size() == 0 &&
1327 estimator->b_timestamps().size() == 0) {
1328 continue;
1329 }
1330
1331 if (VLOG_IS_ON(1)) {
1332 estimator->LogFit(prefix);
1333 }
1334
1335 const Node *const node_a = std::get<0>(filter.first);
1336 const Node *const node_b = std::get<1>(filter.first);
1337
1338 const size_t node_a_index =
1339 configuration::GetNodeIndex(configuration(), node_a);
1340 const size_t node_b_index =
1341 configuration::GetNodeIndex(configuration(), node_b);
1342
1343 const double recovered_slope =
1344 slope(node_b_index) / slope(node_a_index) - 1.0;
1345 const int64_t recovered_offset =
1346 offset(node_b_index).count() - offset(node_a_index).count() *
1347 slope(node_b_index) /
1348 slope(node_a_index);
1349
1350 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1351 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1352 << " offset " << std::setprecision(20) << recovered_offset
1353 << " (error "
1354 << recovered_offset - estimator->fit().offset().count() << ")";
1355
1356 const aos::distributed_clock::time_point a0 =
1357 states_[node_a_index]->ToDistributedClock(
1358 std::get<0>(estimator->a_timestamps()[0]));
1359 const aos::distributed_clock::time_point a1 =
1360 states_[node_a_index]->ToDistributedClock(
1361 std::get<0>(estimator->a_timestamps()[1]));
1362
1363 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1364 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1365 << " distributed -> " << node_b->name()->string_view() << " "
1366 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1367 << aos::monotonic_clock::time_point(
1368 std::chrono::nanoseconds(static_cast<int64_t>(
1369 std::get<0>(estimator->a_timestamps()[0])
1370 .time_since_epoch()
1371 .count() *
1372 (1.0 + estimator->fit().slope()))) +
1373 estimator->fit().offset())
1374 << ((a0 <= event_loop_factory_->distributed_now())
1375 ? ""
1376 : " After now, investigate");
1377 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1378 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1379 << " distributed -> " << node_b->name()->string_view() << " "
1380 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1381 << aos::monotonic_clock::time_point(
1382 std::chrono::nanoseconds(static_cast<int64_t>(
1383 std::get<0>(estimator->a_timestamps()[1])
1384 .time_since_epoch()
1385 .count() *
1386 (1.0 + estimator->fit().slope()))) +
1387 estimator->fit().offset())
1388 << ((event_loop_factory_->distributed_now() <= a1)
1389 ? ""
1390 : " Before now, investigate");
1391
1392 const aos::distributed_clock::time_point b0 =
1393 states_[node_b_index]->ToDistributedClock(
1394 std::get<0>(estimator->b_timestamps()[0]));
1395 const aos::distributed_clock::time_point b1 =
1396 states_[node_b_index]->ToDistributedClock(
1397 std::get<0>(estimator->b_timestamps()[1]));
1398
1399 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1400 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1401 << " distributed -> " << node_a->name()->string_view() << " "
1402 << states_[node_a_index]->FromDistributedClock(b0)
1403 << ((b0 <= event_loop_factory_->distributed_now())
1404 ? ""
1405 : " After now, investigate");
1406 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1407 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1408 << " distributed -> " << node_a->name()->string_view() << " "
1409 << states_[node_a_index]->FromDistributedClock(b1)
1410 << ((event_loop_factory_->distributed_now() <= b1)
1411 ? ""
1412 : " Before now, investigate");
1413 }
1414}
1415
1416message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001417 const Node *node_a, const Node *node_b) {
1418 CHECK_NE(node_a, node_b);
1419 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1420 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1421
1422 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001423 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001424 }
1425
1426 auto tuple = std::make_tuple(node_a, node_b);
1427
1428 auto it = filters_.find(tuple);
1429
1430 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001431 auto &x =
1432 filters_
1433 .insert(std::make_pair(
1434 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1435 node_a, node_b))))
1436 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001437 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001438 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1439 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1440 node_b->name()->string_view()));
1441 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1442 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1443 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001444 }
1445
Austin Schuh2f8fd752020-09-01 22:38:28 -07001446 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001447 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001448 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001449 }
1450}
1451
Austin Schuhe309d2a2019-11-29 13:25:21 -08001452void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001453 State *state =
1454 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1455 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001456
Austin Schuh858c9f32020-08-31 16:56:12 -07001457 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001458
Tyler Chatow67ddb032020-01-12 14:30:04 -08001459 // We don't run timing reports when trying to print out logged data, because
1460 // otherwise we would end up printing out the timing reports themselves...
1461 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001462 event_loop->SkipTimingReport();
1463 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001464
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001465 for (size_t logged_channel_index = 0;
1466 logged_channel_index < logged_configuration()->channels()->size();
1467 ++logged_channel_index) {
1468 const Channel *channel = RemapChannel(
1469 event_loop,
1470 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001471
Austin Schuh2f8fd752020-09-01 22:38:28 -07001472 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001473 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001474
1475 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001476
1477 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1478 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001479 // We've got a message which is being forwarded to this node.
1480 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001481 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001482 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001483
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001484 // Delivery timestamps are supposed to be logged back on the source node.
1485 // Configure remote timestamps to be sent.
1486 const bool delivery_time_is_logged =
1487 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1488 channel, event_loop->node(), source_node);
1489
1490 source_state =
1491 states_[configuration::GetNodeIndex(configuration(), source_node)]
1492 .get();
1493
1494 if (delivery_time_is_logged) {
1495 remote_timestamp_sender =
1496 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001497 }
1498 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001499
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001500 state->SetChannel(
1501 logged_channel_index,
1502 configuration::ChannelIndex(event_loop->configuration(), channel),
1503 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1504 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001505 }
1506
Austin Schuh6aa77be2020-02-22 21:06:40 -08001507 // If we didn't find any log files with data in them, we won't ever get a
1508 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001509 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001510 return;
1511 }
1512
Austin Schuh858c9f32020-08-31 16:56:12 -07001513 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001514 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1515 << "at " << state->event_loop()->context().monotonic_event_time
1516 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001517 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001518 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001519 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001520 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001521 event_loop_factory_->Exit();
1522 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001523 return;
1524 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001525 if (VLOG_IS_ON(1)) {
1526 LogFit("Offset was");
1527 }
1528
1529 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001530 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001531
Austin Schuhe309d2a2019-11-29 13:25:21 -08001532 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001533 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001534 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001535 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001536 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1537 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001538 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001539 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001540 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001541 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001542 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001543 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001544 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001545 << "): " << FlatbufferToJson(state->event_loop()->node())
1546 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001547 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001548 << state->DebugString();
1549 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001550
Austin Schuh287d43d2020-12-04 20:19:33 -08001551 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001552 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001553 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001554 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001555 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001556 timestamped_message.data.span().size() != 0u) {
1557 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001558 << ": Got a message without data on channel "
1559 << configuration::CleanedChannelToString(
1560 logged_configuration()->channels()->Get(
1561 timestamped_message.channel_index))
1562 << ". Forwarding entry which was not matched? Use "
1563 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001564
Austin Schuh2f8fd752020-09-01 22:38:28 -07001565 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001566 // Confirm that the message was sent on the sending node before the
1567 // destination node (this node). As a proxy, do this by making sure
1568 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001569 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001570 CHECK_LT(
1571 timestamped_message.monotonic_remote_time,
1572 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001573 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001574 << state->remote_node(timestamped_message.channel_index)
1575 ->name()
1576 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001577 << " while trying to send a message on "
1578 << configuration::CleanedChannelToString(
1579 logged_configuration()->channels()->Get(
1580 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001581 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001582 } else if (timestamped_message.monotonic_remote_time >=
1583 state->monotonic_remote_now(
1584 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001585 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001586 << "Check failed: timestamped_message.monotonic_remote_time < "
1587 "state->monotonic_remote_now(timestamped_message.channel_"
1588 "index) ("
1589 << timestamped_message.monotonic_remote_time << " vs. "
1590 << state->monotonic_remote_now(
1591 timestamped_message.channel_index)
1592 << ") " << state->event_loop()->node()->name()->string_view()
1593 << " to "
1594 << state->remote_node(timestamped_message.channel_index)
1595 ->name()
1596 ->string_view()
1597 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001598 << " ("
1599 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001600 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001601 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001602 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001603 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001604 timestamped_message.channel_index,
1605 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001606 << ") " << state->DebugString();
1607 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001608
1609 if (FLAGS_timestamps_to_csv) {
1610 if (offset_fp_ == nullptr) {
1611 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1612 fprintf(
1613 offset_fp_,
1614 "# time_since_start, offset node 0, offset node 1, ...\n");
Austin Schuh287d43d2020-12-04 20:19:33 -08001615 first_time_ = timestamped_message.realtime_event_time;
Austin Schuh8bd96322020-02-13 21:18:22 -08001616 }
1617
1618 fprintf(offset_fp_, "%.9f",
1619 std::chrono::duration_cast<std::chrono::duration<double>>(
Austin Schuh287d43d2020-12-04 20:19:33 -08001620 timestamped_message.realtime_event_time - first_time_)
Austin Schuh8bd96322020-02-13 21:18:22 -08001621 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001622 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1623 fprintf(offset_fp_, ", %.9f",
1624 time_offset_matrix_(i, 0) +
1625 time_slope_matrix_(i, 0) *
1626 chrono::duration<double>(
1627 event_loop_factory_->distributed_now()
1628 .time_since_epoch())
1629 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001630 }
1631 fprintf(offset_fp_, "\n");
1632 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001633 }
1634
Austin Schuh15649d62019-12-28 16:36:38 -08001635 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001636 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1637 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001638
Austin Schuh2f8fd752020-09-01 22:38:28 -07001639 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001640 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001641 // TODO(austin): std::move channel_data in and make that efficient in
1642 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001643 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001644 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001645 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001646 // reading the rest of the log file and call it quits. We don't want
1647 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001648 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1649 bool update_time_dummy;
1650 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001651 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001652 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001653 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001654 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001655 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001656 LOG(WARNING)
1657 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001658 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001659 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001660 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001661 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001662 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001663 }
1664
Austin Schuh858c9f32020-08-31 16:56:12 -07001665 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001666 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001667 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1668 << "wakeup for " << next_time << "("
1669 << state->ToDistributedClock(next_time)
1670 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001671 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001672 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001673 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1674 << "No next message, scheduling shutdown";
1675 // Set a timer up immediately after now to die. If we don't do this,
1676 // then the senders waiting on the message we just read will never get
1677 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001678 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001679 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1680 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001681 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001682 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001683
Austin Schuh2f8fd752020-09-01 22:38:28 -07001684 // Once we make this call, the current time changes. So do everything
1685 // which involves time before changing it. That especially includes
1686 // sending the message.
1687 if (update_time) {
1688 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1689 << "updating offsets";
1690
1691 std::vector<aos::monotonic_clock::time_point> before_times;
1692 before_times.resize(states_.size());
1693 std::transform(states_.begin(), states_.end(), before_times.begin(),
1694 [](const std::unique_ptr<State> &state) {
1695 return state->monotonic_now();
1696 });
1697
1698 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001699 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1700 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001701 }
1702
Austin Schuh8bd96322020-02-13 21:18:22 -08001703 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001704 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1705 << state->monotonic_now();
1706
1707 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001708 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1709 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001710 }
1711
1712 // TODO(austin): We should be perfect.
1713 const std::chrono::nanoseconds kTolerance{3};
1714 if (!FLAGS_skip_order_validation) {
1715 CHECK_GE(next_time, state->monotonic_now())
1716 << ": Time skipped the next event.";
1717
1718 for (size_t i = 0; i < states_.size(); ++i) {
1719 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1720 << ": Time changed too much on node "
1721 << MaybeNodeName(states_[i]->event_loop()->node());
1722 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1723 << ": Time changed too much on node "
1724 << states_[i]->event_loop()->node()->name()->string_view();
1725 }
1726 } else {
1727 if (next_time < state->monotonic_now()) {
1728 LOG(WARNING) << "Check failed: next_time >= "
1729 "state->monotonic_now() ("
1730 << next_time << " vs. " << state->monotonic_now()
1731 << "): Time skipped the next event.";
1732 }
1733 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001734 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001735 LOG(WARNING) << "Check failed: "
1736 "states_[i]->monotonic_now() "
1737 ">= before_times[i] - kTolerance ("
1738 << states_[i]->monotonic_now() << " vs. "
1739 << before_times[i] - kTolerance
1740 << ") : Time changed too much on node "
1741 << MaybeNodeName(states_[i]->event_loop()->node());
1742 }
Austin Schuh724032b2020-12-18 22:54:59 -08001743 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001744 LOG(WARNING) << "Check failed: "
1745 "states_[i]->monotonic_now() "
1746 "<= before_times[i] + kTolerance ("
1747 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001748 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001749 << ") : Time changed too much on node "
1750 << MaybeNodeName(states_[i]->event_loop()->node());
1751 }
1752 }
1753 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001754 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001755
1756 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1757 << state->event_loop()->context().monotonic_event_time << " now "
1758 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001759 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001760
Austin Schuh6f3babe2020-01-26 20:34:50 -08001761 ++live_nodes_;
1762
Austin Schuh858c9f32020-08-31 16:56:12 -07001763 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1764 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001765 }
1766}
1767
1768void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001769 // Make sure that things get destroyed in the correct order, rather than
1770 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001771 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001772 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001773 }
Austin Schuh92547522019-12-28 14:33:43 -08001774
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001775 event_loop_factory_unique_ptr_.reset();
1776 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001777}
1778
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001779void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001780 std::string_view add_prefix,
1781 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001782 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1783 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1784 if (channel->name()->str() == name &&
1785 channel->type()->string_view() == type) {
1786 CHECK_EQ(0u, remapped_channels_.count(ii))
1787 << "Already remapped channel "
1788 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001789 RemappedChannel remapped_channel;
1790 remapped_channel.remapped_name =
1791 std::string(add_prefix) + std::string(name);
1792 remapped_channel.new_type = new_type;
1793 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001794 VLOG(1) << "Remapping channel "
1795 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001796 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001797 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001798 return;
1799 }
1800 }
1801 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1802 << type;
1803}
1804
Austin Schuh01b4c352020-09-21 23:09:39 -07001805void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1806 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001807 std::string_view add_prefix,
1808 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001809 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1810 const Channel *remapped_channel =
1811 configuration::GetChannel(logged_configuration(), name, type, "", node);
1812 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1813 << "\", \"type\": \"" << type << "\"}";
1814 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1815 << "\"}";
1816 VLOG(1) << "Remapped "
1817 << aos::configuration::StrippedChannelToString(remapped_channel);
1818
1819 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1820 // we want it to degrade if the heuristics fail to just work.
1821 //
1822 // The easiest way to do this is going to be incredibly specific and verbose.
1823 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1824 // /original/0/spray. Then, create a map from /original/spray to
1825 // /original/0/spray for just the type we were asked for.
1826 if (name != remapped_channel->name()->string_view()) {
1827 MapT new_map;
1828 new_map.match = std::make_unique<ChannelT>();
1829 new_map.match->name = absl::StrCat(add_prefix, name);
1830 new_map.match->type = type;
1831 if (node != nullptr) {
1832 new_map.match->source_node = node->name()->str();
1833 }
1834 new_map.rename = std::make_unique<ChannelT>();
1835 new_map.rename->name =
1836 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1837 maps_.emplace_back(std::move(new_map));
1838 }
1839
1840 const size_t channel_index =
1841 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1842 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1843 << "Already remapped channel "
1844 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001845
1846 RemappedChannel remapped_channel_struct;
1847 remapped_channel_struct.remapped_name =
1848 std::string(add_prefix) +
1849 std::string(remapped_channel->name()->string_view());
1850 remapped_channel_struct.new_type = new_type;
1851 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001852 MakeRemappedConfig();
1853}
1854
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001855void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001856 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001857 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001858 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001859 << ": Can't change the mapping after the events are scheduled.";
1860 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001861 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001862
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001863 // If no remapping occurred and we are using the original config, then there
1864 // is nothing interesting to do here.
1865 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001866 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001867 return;
1868 }
1869 // Config to copy Channel definitions from. Use the specified
1870 // replay_configuration_ if it has been provided.
1871 const Configuration *const base_config = replay_configuration_ == nullptr
1872 ? logged_configuration()
1873 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001874
1875 // Create a config with all the channels, but un-sorted/merged. Collect up
1876 // the schemas while we do this. Call MergeConfiguration to sort everything,
1877 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001878
1879 // This is the builder that we use for the config containing all the new
1880 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001881 flatbuffers::FlatBufferBuilder fbb;
1882 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001883 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001884
1885 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1886 << ": Merging logic needs to be updated when the number of channel "
1887 "fields changes.";
1888
1889 // List of schemas.
1890 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1891 // Make sure our new RemoteMessage schema is in there for old logs without it.
1892 schema_map.insert(std::make_pair(
1893 RemoteMessage::GetFullyQualifiedName(),
1894 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1895 message_bridge::RemoteMessageSchema()))));
1896
1897 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001898 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001899 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001900 base_config, logged_configuration()->channels()->Get(pair.first), "",
1901 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001902 channel_offsets.emplace_back(
1903 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001904 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001905
Austin Schuh0de30f32020-12-06 12:44:28 -08001906 // Now reconstruct the original channels, translating types as needed
1907 for (const Channel *c : *base_config->channels()) {
1908 // Search for a mapping channel.
1909 std::string_view new_type = "";
1910 for (auto &pair : remapped_channels_) {
1911 const Channel *const remapped_channel =
1912 logged_configuration()->channels()->Get(pair.first);
1913 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1914 remapped_channel->type()->string_view() == c->type()->string_view()) {
1915 new_type = pair.second.new_type;
1916 break;
1917 }
1918 }
1919
1920 // Copy everything over.
1921 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1922
1923 // Add the schema if it doesn't exist.
1924 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1925 CHECK(c->has_schema());
1926 schema_map.insert(std::make_pair(c->type()->string_view(),
1927 RecursiveCopyFlatBuffer(c->schema())));
1928 }
1929 }
1930
1931 // The MergeConfiguration API takes a vector, not a map. Convert.
1932 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1933 while (!schema_map.empty()) {
1934 schemas.emplace_back(std::move(schema_map.begin()->second));
1935 schema_map.erase(schema_map.begin());
1936 }
1937
1938 // Create the Configuration containing the new channels that we want to add.
1939 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1940 channels_offset =
1941 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1942
1943 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001944 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001945 if (base_config->maps()) {
1946 for (const Map *map : *base_config->maps()) {
1947 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1948 }
1949 }
1950
1951 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001952 for (const MapT &map : maps_) {
1953 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001954 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001955 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001956 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001957 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001958 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001959 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1960 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001961 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001962 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001963 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001964 match_builder.add_name(match_name_offset);
1965 match_builder.add_type(match_type_offset);
1966 if (!map.match->source_node.empty()) {
1967 match_builder.add_source_node(match_source_node_offset);
1968 }
1969 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1970
Austin Schuh0de30f32020-12-06 12:44:28 -08001971 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001972 rename_builder.add_name(rename_name_offset);
1973 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1974
Austin Schuh0de30f32020-12-06 12:44:28 -08001975 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001976 map_builder.add_match(match_offset);
1977 map_builder.add_rename(rename_offset);
1978 map_offsets.emplace_back(map_builder.Finish());
1979 }
1980
Austin Schuh0de30f32020-12-06 12:44:28 -08001981 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1982 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001983
Austin Schuh0de30f32020-12-06 12:44:28 -08001984 // And copy everything else over.
1985 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1986 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1987
1988 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1989 applications_offset =
1990 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1991
1992 // Now insert everything else in unmodified.
1993 ConfigurationBuilder configuration_builder(fbb);
1994 if (!channels_offset.IsNull()) {
1995 configuration_builder.add_channels(channels_offset);
1996 }
1997 if (!maps_offsets.IsNull()) {
1998 configuration_builder.add_maps(maps_offsets);
1999 }
2000 if (!nodes_offset.IsNull()) {
2001 configuration_builder.add_nodes(nodes_offset);
2002 }
2003 if (!applications_offset.IsNull()) {
2004 configuration_builder.add_applications(applications_offset);
2005 }
2006
2007 if (base_config->has_channel_storage_duration()) {
2008 configuration_builder.add_channel_storage_duration(
2009 base_config->channel_storage_duration());
2010 }
2011
2012 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
2013 << ": Merging logic needs to be updated when the number of configuration "
2014 "fields changes.";
2015
2016 fbb.Finish(configuration_builder.Finish());
2017
2018 // Clean it up and return it! By using MergeConfiguration here, we'll
2019 // actually get a deduplicated config for free too.
2020 FlatbufferDetachedBuffer<Configuration> new_merged_config =
2021 configuration::MergeConfiguration(
2022 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
2023
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002024 remapped_configuration_buffer_ =
2025 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08002026 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002027
2028 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08002029
2030 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002031}
2032
Austin Schuh6f3babe2020-01-26 20:34:50 -08002033const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
2034 const Channel *channel) {
2035 std::string_view channel_name = channel->name()->string_view();
2036 std::string_view channel_type = channel->type()->string_view();
2037 const int channel_index =
2038 configuration::ChannelIndex(logged_configuration(), channel);
2039 // If the channel is remapped, find the correct channel name to use.
2040 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07002041 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08002042 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08002043 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08002044 }
2045
Austin Schuhee711052020-08-24 16:06:09 -07002046 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08002047 const Channel *remapped_channel = configuration::GetChannel(
2048 event_loop->configuration(), channel_name, channel_type,
2049 event_loop->name(), event_loop->node());
2050
2051 CHECK(remapped_channel != nullptr)
2052 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
2053 << channel_type << "\"} because it is not in the provided configuration.";
2054
2055 return remapped_channel;
2056}
2057
Austin Schuh287d43d2020-12-04 20:19:33 -08002058LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
2059 : timestamp_mapper_(std::move(timestamp_mapper)) {}
2060
2061void LogReader::State::AddPeer(State *peer) {
2062 if (timestamp_mapper_ && peer->timestamp_mapper_) {
2063 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
2064 }
2065}
Austin Schuh858c9f32020-08-31 16:56:12 -07002066
2067EventLoop *LogReader::State::SetNodeEventLoopFactory(
2068 NodeEventLoopFactory *node_event_loop_factory) {
2069 node_event_loop_factory_ = node_event_loop_factory;
2070 event_loop_unique_ptr_ =
2071 node_event_loop_factory_->MakeEventLoop("log_reader");
2072 return event_loop_unique_ptr_.get();
2073}
2074
2075void LogReader::State::SetChannelCount(size_t count) {
2076 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002077 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07002078 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002079 channel_source_state_.resize(count);
2080 factory_channel_index_.resize(count);
2081 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07002082}
2083
2084void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002085 size_t logged_channel_index, size_t factory_channel_index,
2086 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07002087 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08002088 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002089 channels_[logged_channel_index] = std::move(sender);
2090 filters_[logged_channel_index] = filter;
2091 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
2092
2093 if (source_state) {
2094 channel_source_state_[logged_channel_index] = source_state;
2095
2096 if (remote_timestamp_sender != nullptr) {
2097 source_state->queue_index_map_[logged_channel_index] =
2098 std::make_unique<std::vector<State::SentTimestamp>>();
2099 }
2100 }
2101
2102 factory_channel_index_[logged_channel_index] = factory_channel_index;
2103}
2104
Austin Schuh287d43d2020-12-04 20:19:33 -08002105bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
2106 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002107 uint32_t remote_queue_index = 0xffffffff;
2108
Austin Schuh287d43d2020-12-04 20:19:33 -08002109 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
2110 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
2111 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
2112 ->queue_index_map_[timestamped_message.channel_index]
2113 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002114
2115 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08002116 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
2117 search.realtime_event_time = timestamped_message.realtime_remote_time;
2118 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002119
2120 // Find the sent time if available.
2121 auto element = std::lower_bound(
2122 queue_index_map->begin(), queue_index_map->end(), search,
2123 [](SentTimestamp a, SentTimestamp b) {
2124 if (b.monotonic_event_time < a.monotonic_event_time) {
2125 return false;
2126 }
2127 if (b.monotonic_event_time > a.monotonic_event_time) {
2128 return true;
2129 }
2130
2131 if (b.queue_index < a.queue_index) {
2132 return false;
2133 }
2134 if (b.queue_index > a.queue_index) {
2135 return true;
2136 }
2137
2138 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
2139 return false;
2140 });
2141
2142 // TODO(austin): Be a bit more principled here, but we will want to do that
2143 // after the logger rewrite. We hit this when one node finishes, but the
2144 // other node isn't done yet. So there is no send time, but there is a
2145 // receive time.
2146 if (element != queue_index_map->end()) {
2147 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08002148 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002149 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08002150 timestamped_message.realtime_remote_time);
2151 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002152
2153 remote_queue_index = element->actual_queue_index;
2154 }
2155 }
2156
2157 // Send! Use the replayed queue index here instead of the logged queue index
2158 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08002159 const bool sent = sender->Send(
2160 timestamped_message.data.message().data()->Data(),
2161 timestamped_message.data.message().data()->size(),
2162 timestamped_message.monotonic_remote_time,
2163 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002164 if (!sent) return false;
2165
Austin Schuh287d43d2020-12-04 20:19:33 -08002166 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002167 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08002168 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
2169 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
2170 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002171 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08002172 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2173 timestamp);
2174 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2175 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08002176 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08002177 remote_timestamp_senders_[timestamped_message.channel_index]
2178 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002179
Austin Schuh315b96b2020-12-11 21:21:12 -08002180 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
2181 builder.fbb()->CreateString(event_loop_->boot_uuid().string_view());
2182
Austin Schuh0de30f32020-12-06 12:44:28 -08002183 RemoteMessage::Builder message_header_builder =
2184 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002185
2186 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002187 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002188
2189 // Swap the remote and sent metrics. They are from the sender's
2190 // perspective, not the receiver's perspective.
2191 message_header_builder.add_monotonic_sent_time(
2192 sender->monotonic_sent_time().time_since_epoch().count());
2193 message_header_builder.add_realtime_sent_time(
2194 sender->realtime_sent_time().time_since_epoch().count());
2195 message_header_builder.add_queue_index(sender->sent_queue_index());
2196
2197 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002198 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002199 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002200 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002201
2202 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002203 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002204
2205 builder.Send(message_header_builder.Finish());
2206 }
2207
2208 return true;
2209}
2210
Austin Schuh0de30f32020-12-06 12:44:28 -08002211aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002212 const Node *delivered_node) {
2213 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2214
2215 if (sender == remote_timestamp_senders_map_.end()) {
2216 sender = remote_timestamp_senders_map_
2217 .emplace(std::make_pair(
2218 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08002219 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002220 absl::StrCat("/aos/remote_timestamps/",
2221 delivered_node->name()->string_view()))))
2222 .first;
2223 }
2224
2225 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07002226}
2227
Austin Schuh287d43d2020-12-04 20:19:33 -08002228TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002229 CHECK_GT(sorted_messages_.size(), 0u);
2230
Austin Schuh287d43d2020-12-04 20:19:33 -08002231 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002232 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002233 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002234 << std::get<0>(result).monotonic_event_time;
2235 sorted_messages_.pop_front();
2236 SeedSortedMessages();
2237
Austin Schuh287d43d2020-12-04 20:19:33 -08002238 if (std::get<1>(result) != nullptr) {
2239 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002240 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2241 } else {
2242 *update_time = false;
2243 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002244 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002245}
2246
2247monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2248 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002249 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002250 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2251 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2252 }
2253
Austin Schuh287d43d2020-12-04 20:19:33 -08002254 TimestampedMessage *m =
2255 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2256 if (m == nullptr) {
2257 return monotonic_clock::max_time;
2258 }
2259 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002260}
2261
2262void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002263 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002264 const aos::monotonic_clock::time_point end_queue_time =
2265 (sorted_messages_.size() > 0
2266 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002267 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002268 chrono::duration_cast<chrono::seconds>(
2269 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002270
2271 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002272 TimestampedMessage *m = timestamp_mapper_->Front();
2273 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002274 return;
2275 }
2276 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002277 // Stop placing sorted messages on the list once we have
2278 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2279 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002280 if (end_queue_time <
2281 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2282 return;
2283 }
2284 }
2285
Austin Schuh2f8fd752020-09-01 22:38:28 -07002286 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2287
Austin Schuh287d43d2020-12-04 20:19:33 -08002288 TimestampedMessage timestamped_message = std::move(*m);
2289 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002290
Austin Schuh2f8fd752020-09-01 22:38:28 -07002291 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002292 if (timestamped_message.monotonic_remote_time !=
2293 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002294 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002295 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002296
2297 CHECK(filter != nullptr);
2298
2299 // Call the correct method depending on if we are the forward or
2300 // reverse direction here.
2301 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002302 timestamped_message.monotonic_event_time,
2303 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002304 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002305 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002306 }
2307}
2308
2309void LogReader::State::Deregister() {
2310 for (size_t i = 0; i < channels_.size(); ++i) {
2311 channels_[i].reset();
2312 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002313 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002314 event_loop_unique_ptr_.reset();
2315 event_loop_ = nullptr;
2316 timer_handler_ = nullptr;
2317 node_event_loop_factory_ = nullptr;
2318}
2319
Austin Schuhe309d2a2019-11-29 13:25:21 -08002320} // namespace logger
2321} // namespace aos