blob: a8bf77cb3f1c4bf45b705209f85cdbd13f3b7130 [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 Schuhe309d2a2019-11-29 13:25:21 -080038namespace aos {
39namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070040namespace {
41// Helper to safely read a header, or CHECK.
Austin Schuhadd6eb32020-11-09 21:24:26 -080042SizePrefixedFlatbufferVector<LogFileHeader> MaybeReadHeaderOrDie(
Austin Schuh287d43d2020-12-04 20:19:33 -080043 const std::vector<LogFile> &log_files) {
44 CHECK_GE(log_files.size(), 1u) << ": Empty filenames list";
45 CHECK_GE(log_files[0].parts.size(), 1u) << ": Empty filenames list";
46 CHECK_GE(log_files[0].parts[0].parts.size(), 1u) << ": Empty filenames list";
Austin Schuhadd6eb32020-11-09 21:24:26 -080047 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> result =
Austin Schuh287d43d2020-12-04 20:19:33 -080048 ReadHeader(log_files[0].parts[0].parts[0]);
Austin Schuh3bd4c402020-11-06 18:19:06 -080049 CHECK(result);
50 return result.value();
Austin Schuh0afc4d12020-10-19 11:42:04 -070051}
Austin Schuh0de30f32020-12-06 12:44:28 -080052
53// Copies the channel, removing the schema as we go. If new_name is provided,
54// it is used instead of the name inside the channel. If new_type is provided,
55// it is used instead of the type in the channel.
56flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
57 std::string_view new_name,
58 std::string_view new_type,
59 flatbuffers::FlatBufferBuilder *fbb) {
60 flatbuffers::Offset<flatbuffers::String> name_offset =
61 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
62 : new_name);
63 flatbuffers::Offset<flatbuffers::String> type_offset =
64 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
65 flatbuffers::Offset<flatbuffers::String> source_node_offset =
66 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
67 : 0;
68
69 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
70 destination_nodes_offset =
71 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
72
73 flatbuffers::Offset<
74 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
75 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
76
77 Channel::Builder channel_builder(*fbb);
78 channel_builder.add_name(name_offset);
79 channel_builder.add_type(type_offset);
80 if (c->has_frequency()) {
81 channel_builder.add_frequency(c->frequency());
82 }
83 if (c->has_max_size()) {
84 channel_builder.add_max_size(c->max_size());
85 }
86 if (c->has_num_senders()) {
87 channel_builder.add_num_senders(c->num_senders());
88 }
89 if (c->has_num_watchers()) {
90 channel_builder.add_num_watchers(c->num_watchers());
91 }
92 if (!source_node_offset.IsNull()) {
93 channel_builder.add_source_node(source_node_offset);
94 }
95 if (!destination_nodes_offset.IsNull()) {
96 channel_builder.add_destination_nodes(destination_nodes_offset);
97 }
98 if (c->has_logger()) {
99 channel_builder.add_logger(c->logger());
100 }
101 if (!logger_nodes_offset.IsNull()) {
102 channel_builder.add_logger_nodes(logger_nodes_offset);
103 }
104 if (c->has_read_method()) {
105 channel_builder.add_read_method(c->read_method());
106 }
107 if (c->has_num_readers()) {
108 channel_builder.add_num_readers(c->num_readers());
109 }
110 return channel_builder.Finish();
111}
112
Austin Schuhe309d2a2019-11-29 13:25:21 -0800113namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800114using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700115} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800116
Brian Silverman1f345222020-09-24 21:14:48 -0700117Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
118 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800119 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700120 configuration_(configuration),
Brian Silvermanae7c0332020-09-30 16:58:23 -0700121 boot_uuid_(
122 util::ReadFileToStringOrDie("/proc/sys/kernel/random/boot_id")),
Austin Schuh0c297012020-09-16 18:41:59 -0700123 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700124 timer_handler_(event_loop_->AddTimer(
125 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700126 server_statistics_fetcher_(
127 configuration::MultiNode(event_loop_->configuration())
128 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
129 "/aos")
130 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700131 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700132
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700133 // Find all the nodes which are logging timestamps on our node. This may
134 // over-estimate if should_log is specified.
135 std::vector<const Node *> timestamp_logger_nodes =
136 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700137
138 std::map<const Channel *, const Node *> timestamp_logger_channels;
139
140 // Now that we have all the nodes accumulated, make remote timestamp loggers
141 // for them.
142 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700143 // Note: since we are doing a find using the event loop channel, we need to
144 // make sure this channel pointer is part of the event loop configuration,
145 // not configuration_. This only matters when configuration_ !=
146 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700148 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700149 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800150 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700151 event_loop_->node());
152
153 CHECK(channel != nullptr)
154 << ": Remote timestamps are logged on "
155 << event_loop_->node()->name()->string_view()
156 << " but can't find channel /aos/remote_timestamps/"
157 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700158 if (!should_log(channel)) {
159 continue;
160 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700161 timestamp_logger_channels.insert(std::make_pair(channel, node));
162 }
163
Brian Silvermand90905f2020-09-23 14:42:56 -0700164 const size_t our_node_index =
165 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700166
Brian Silverman1f345222020-09-24 21:14:48 -0700167 for (size_t channel_index = 0;
168 channel_index < configuration_->channels()->size(); ++channel_index) {
169 const Channel *const config_channel =
170 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700171 // The MakeRawFetcher method needs a channel which is in the event loop
172 // configuration() object, not the configuration_ object. Go look that up
173 // from the config.
174 const Channel *channel = aos::configuration::GetChannel(
175 event_loop_->configuration(), config_channel->name()->string_view(),
176 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700177 CHECK(channel != nullptr)
178 << ": Failed to look up channel "
179 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700180 if (!should_log(channel)) {
181 continue;
182 }
Austin Schuh0c297012020-09-16 18:41:59 -0700183
Austin Schuhe309d2a2019-11-29 13:25:21 -0800184 FetcherStruct fs;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700185 fs.node_index = our_node_index;
Brian Silverman1f345222020-09-24 21:14:48 -0700186 fs.channel_index = channel_index;
187 fs.channel = channel;
188
Austin Schuh6f3babe2020-01-26 20:34:50 -0800189 const bool is_local =
190 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
191
Austin Schuh15649d62019-12-28 16:36:38 -0800192 const bool is_readable =
193 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700194 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
195 channel, event_loop_->node());
196 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800197
Brian Silverman1f345222020-09-24 21:14:48 -0700198 bool log_delivery_times = false;
199 if (event_loop_->node() != nullptr) {
200 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
201 channel, event_loop_->node(), event_loop_->node());
202 }
Austin Schuh15649d62019-12-28 16:36:38 -0800203
Austin Schuh0de30f32020-12-06 12:44:28 -0800204 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700205 // contents to a file directly.
206 const bool log_contents = timestamp_logger_channels.find(channel) !=
207 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700208
209 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800210 fs.fetcher = event_loop->MakeRawFetcher(channel);
211 VLOG(1) << "Logging channel "
212 << configuration::CleanedChannelToString(channel);
213
214 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800215 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700216 fs.wants_timestamp_writer = true;
Austin Schuh15649d62019-12-28 16:36:38 -0800217 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800218 if (log_message) {
219 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700220 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800221 if (!is_local) {
222 fs.log_type = LogType::kLogRemoteMessage;
223 }
224 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700225 if (log_contents) {
226 VLOG(1) << "Timestamp logger channel "
227 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700228 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
229 fs.wants_contents_writer = true;
Austin Schuh0c297012020-09-16 18:41:59 -0700230 fs.node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700231 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700232 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800233 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800234 }
Brian Silverman1f345222020-09-24 21:14:48 -0700235 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700236
237 // When we are logging remote timestamps, we need to be able to translate from
238 // the channel index that the event loop uses to the channel index in the
239 // config in the log file.
240 event_loop_to_logged_channel_index_.resize(
241 event_loop->configuration()->channels()->size(), -1);
242 for (size_t event_loop_channel_index = 0;
243 event_loop_channel_index <
244 event_loop->configuration()->channels()->size();
245 ++event_loop_channel_index) {
246 const Channel *event_loop_channel =
247 event_loop->configuration()->channels()->Get(event_loop_channel_index);
248
249 const Channel *logged_channel = aos::configuration::GetChannel(
250 configuration_, event_loop_channel->name()->string_view(),
251 event_loop_channel->type()->string_view(), "",
252 configuration::GetNode(configuration_, event_loop_->node()));
253
254 if (logged_channel != nullptr) {
255 event_loop_to_logged_channel_index_[event_loop_channel_index] =
256 configuration::ChannelIndex(configuration_, logged_channel);
257 }
258 }
Brian Silverman1f345222020-09-24 21:14:48 -0700259}
260
261Logger::~Logger() {
262 if (log_namer_) {
263 // If we are replaying a log file, or in simulation, we want to force the
264 // last bit of data to be logged. The easiest way to deal with this is to
265 // poll everything as we go to destroy the class, ie, shut down the logger,
266 // and write it to disk.
267 StopLogging(event_loop_->monotonic_now());
268 }
269}
270
Brian Silvermanae7c0332020-09-30 16:58:23 -0700271void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
272 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700273 CHECK(!log_namer_) << ": Already logging";
274 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700275 log_event_uuid_ = UUID::Random();
276 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700277 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
278
279 // We want to do as much work as possible before the initial Fetch. Time
280 // between that and actually starting to log opens up the possibility of
281 // falling off the end of the queue during that time.
282
283 for (FetcherStruct &f : fetchers_) {
284 if (f.wants_writer) {
285 f.writer = log_namer_->MakeWriter(f.channel);
286 }
287 if (f.wants_timestamp_writer) {
288 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
289 }
290 if (f.wants_contents_writer) {
291 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
292 f.channel, CHECK_NOTNULL(f.timestamp_node));
293 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800294 }
295
Brian Silverman1f345222020-09-24 21:14:48 -0700296 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700297 node_state_.resize(configuration::MultiNode(configuration_)
298 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700299 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800300
Austin Schuh2f8fd752020-09-01 22:38:28 -0700301 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700302 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800303
Austin Schuh2f8fd752020-09-01 22:38:28 -0700304 node_state_[node_index].log_file_header = MakeHeader(node);
305 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800306
Austin Schuh2f8fd752020-09-01 22:38:28 -0700307 // Grab data from each channel right before we declare the log file started
308 // so we can capture the latest message on each channel. This lets us have
309 // non periodic messages with configuration that now get logged.
310 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700311 const auto start = event_loop_->monotonic_now();
312 const bool got_new = f.fetcher->Fetch();
313 const auto end = event_loop_->monotonic_now();
314 RecordFetchResult(start, end, got_new, &f);
315
316 // If there is a message, we want to write it.
317 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700318 }
319
320 // Clear out any old timestamps in case we are re-starting logging.
321 for (size_t i = 0; i < node_state_.size(); ++i) {
322 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time);
323 }
324
325 WriteHeader();
326
327 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
328 << " start_time " << last_synchronized_time_;
329
330 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
331 polling_period_);
332}
333
Brian Silverman1f345222020-09-24 21:14:48 -0700334std::unique_ptr<LogNamer> Logger::StopLogging(
335 aos::monotonic_clock::time_point end_time) {
336 CHECK(log_namer_) << ": Not logging right now";
337
338 if (end_time != aos::monotonic_clock::min_time) {
339 LogUntil(end_time);
340 }
341 timer_handler_->Disable();
342
343 for (FetcherStruct &f : fetchers_) {
344 f.writer = nullptr;
345 f.timestamp_writer = nullptr;
346 f.contents_writer = nullptr;
347 }
348 node_state_.clear();
349
Brian Silvermanae7c0332020-09-30 16:58:23 -0700350 log_event_uuid_ = UUID::Zero();
351 log_start_uuid_ = std::string();
352
Brian Silverman1f345222020-09-24 21:14:48 -0700353 return std::move(log_namer_);
354}
355
Austin Schuhfa895892020-01-07 20:07:41 -0800356void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700357 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 server_statistics_fetcher_.Fetch();
359 }
360
361 aos::monotonic_clock::time_point monotonic_start_time =
362 event_loop_->monotonic_now();
363 aos::realtime_clock::time_point realtime_start_time =
364 event_loop_->realtime_now();
365
366 // We need to pick a point in time to declare the log file "started". This
367 // starts here. It needs to be after everything is fetched so that the
368 // fetchers are all pointed at the most recent message before the start
369 // time.
370 last_synchronized_time_ = monotonic_start_time;
371
Austin Schuh6f3babe2020-01-26 20:34:50 -0800372 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700373 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700374 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
375 realtime_start_time);
Austin Schuh64fab802020-09-09 22:47:47 -0700376 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800377 }
378}
Austin Schuh8bd96322020-02-13 21:18:22 -0800379
Austin Schuh2f8fd752020-09-01 22:38:28 -0700380void Logger::WriteMissingTimestamps() {
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 } else {
384 return;
385 }
386
387 if (server_statistics_fetcher_.get() == nullptr) {
388 return;
389 }
390
391 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700392 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700393 if (MaybeUpdateTimestamp(
394 node, node_index,
395 server_statistics_fetcher_.context().monotonic_event_time,
396 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh64fab802020-09-09 22:47:47 -0700397 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700398 }
399 }
400}
401
402void Logger::SetStartTime(size_t node_index,
403 aos::monotonic_clock::time_point monotonic_start_time,
404 aos::realtime_clock::time_point realtime_start_time) {
405 node_state_[node_index].monotonic_start_time = monotonic_start_time;
406 node_state_[node_index].realtime_start_time = realtime_start_time;
407 node_state_[node_index]
408 .log_file_header.mutable_message()
409 ->mutate_monotonic_start_time(
410 std::chrono::duration_cast<std::chrono::nanoseconds>(
411 monotonic_start_time.time_since_epoch())
412 .count());
413 if (node_state_[node_index]
414 .log_file_header.mutable_message()
415 ->has_realtime_start_time()) {
416 node_state_[node_index]
417 .log_file_header.mutable_message()
418 ->mutate_realtime_start_time(
419 std::chrono::duration_cast<std::chrono::nanoseconds>(
420 realtime_start_time.time_since_epoch())
421 .count());
422 }
423}
424
425bool Logger::MaybeUpdateTimestamp(
426 const Node *node, int node_index,
427 aos::monotonic_clock::time_point monotonic_start_time,
428 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700429 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700430 if (node_state_[node_index].monotonic_start_time !=
431 monotonic_clock::min_time) {
432 return false;
433 }
Austin Schuh0c297012020-09-16 18:41:59 -0700434 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700435 if (event_loop_->node() == node) {
436 // There are no offsets to compute for ourself, so always succeed.
437 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
438 return true;
439 } else if (server_statistics_fetcher_.get() != nullptr) {
440 // We must be a remote node now. Look for the connection and see if it is
441 // connected.
442
443 for (const message_bridge::ServerConnection *connection :
444 *server_statistics_fetcher_->connections()) {
445 if (connection->node()->name()->string_view() !=
446 node->name()->string_view()) {
447 continue;
448 }
449
450 if (connection->state() != message_bridge::State::CONNECTED) {
451 VLOG(1) << node->name()->string_view()
452 << " is not connected, can't start it yet.";
453 break;
454 }
455
456 if (!connection->has_monotonic_offset()) {
457 VLOG(1) << "Missing monotonic offset for setting start time for node "
458 << aos::FlatbufferToJson(node);
459 break;
460 }
461
462 VLOG(1) << "Updating start time for " << aos::FlatbufferToJson(node);
463
464 // Found it and it is connected. Compensate and go.
465 monotonic_start_time +=
466 std::chrono::nanoseconds(connection->monotonic_offset());
467
468 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
469 return true;
470 }
471 }
472 } else {
473 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
474 return true;
475 }
476 return false;
477}
478
479aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
480 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800481 // Now write the header with this timestamp in it.
482 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800483 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800484
Austin Schuh2f8fd752020-09-01 22:38:28 -0700485 // TODO(austin): Compress this much more efficiently. There are a bunch of
486 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700487 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700488 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800489
Brian Silvermanae7c0332020-09-30 16:58:23 -0700490 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700491 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800492
Brian Silvermanae7c0332020-09-30 16:58:23 -0700493 CHECK(log_event_uuid_ != UUID::Zero());
494 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
495 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700496
Brian Silvermanae7c0332020-09-30 16:58:23 -0700497 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
498 fbb.CreateString(logger_instance_uuid_.string_view());
499
500 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
501 if (!log_start_uuid_.empty()) {
502 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
503 }
504
505 const flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
506 fbb.CreateString(boot_uuid_);
507
508 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700509 fbb.CreateString("00000000-0000-4000-8000-000000000000");
510
Austin Schuhfa895892020-01-07 20:07:41 -0800511 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700512 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700513
Austin Schuh0c297012020-09-16 18:41:59 -0700514 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800515 // TODO(austin): Reuse the node we just copied in above.
516 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
517 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800518 }
519
520 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
521
Austin Schuh64fab802020-09-09 22:47:47 -0700522 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800523
524 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800525 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800526 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700527 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800528 }
529
530 log_file_header_builder.add_configuration(configuration_offset);
531 // The worst case theoretical out of order is the polling period times 2.
532 // One message could get logged right after the boundary, but be for right
533 // before the next boundary. And the reverse could happen for another
534 // message. Report back 3x to be extra safe, and because the cost isn't
535 // huge on the read side.
536 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700537 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800538
539 log_file_header_builder.add_monotonic_start_time(
540 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700541 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800542 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700543 if (node == event_loop_->node()) {
544 log_file_header_builder.add_realtime_start_time(
545 std::chrono::duration_cast<std::chrono::nanoseconds>(
546 realtime_clock::min_time.time_since_epoch())
547 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800548 }
549
Brian Silvermanae7c0332020-09-30 16:58:23 -0700550 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
551 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
552 if (!log_start_uuid_offset.IsNull()) {
553 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
554 }
555 log_file_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700556
557 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
558 log_file_header_builder.add_parts_index(0);
559
Austin Schuh2f8fd752020-09-01 22:38:28 -0700560 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800561 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
562 fbb.Release());
563
564 CHECK(result.Verify()) << ": Built a corrupted header.";
565
566 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700567}
568
Brian Silvermancb805822020-10-06 17:43:35 -0700569void Logger::ResetStatisics() {
570 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
571 max_message_fetch_time_channel_ = -1;
572 max_message_fetch_time_size_ = -1;
573 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
574 total_message_fetch_count_ = 0;
575 total_message_fetch_bytes_ = 0;
576 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
577 total_nop_fetch_count_ = 0;
578 max_copy_time_ = std::chrono::nanoseconds::zero();
579 max_copy_time_channel_ = -1;
580 max_copy_time_size_ = -1;
581 total_copy_time_ = std::chrono::nanoseconds::zero();
582 total_copy_count_ = 0;
583 total_copy_bytes_ = 0;
584}
585
Austin Schuh2f8fd752020-09-01 22:38:28 -0700586void Logger::Rotate() {
587 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700588 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700589 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700590 }
591}
592
593void Logger::LogUntil(monotonic_clock::time_point t) {
594 WriteMissingTimestamps();
595
596 // Write each channel to disk, one at a time.
597 for (FetcherStruct &f : fetchers_) {
598 while (true) {
599 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700600 const auto start = event_loop_->monotonic_now();
601 const bool got_new = f.fetcher->FetchNext();
602 const auto end = event_loop_->monotonic_now();
603 RecordFetchResult(start, end, got_new, &f);
604 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700605 VLOG(2) << "No new data on "
606 << configuration::CleanedChannelToString(
607 f.fetcher->channel());
608 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700609 }
Brian Silvermancb805822020-10-06 17:43:35 -0700610 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700611 }
612
Austin Schuh2f8fd752020-09-01 22:38:28 -0700613 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700614 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700615 break;
616 }
Brian Silvermancb805822020-10-06 17:43:35 -0700617 if (f.writer != nullptr) {
618 // Write!
619 const auto start = event_loop_->monotonic_now();
620 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
621 max_header_size_);
622 fbb.ForceDefaults(true);
623
624 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
625 f.channel_index, f.log_type));
626 const auto end = event_loop_->monotonic_now();
627 RecordCreateMessageTime(start, end, &f);
628
629 VLOG(2) << "Writing data as node "
630 << FlatbufferToJson(event_loop_->node()) << " for channel "
631 << configuration::CleanedChannelToString(f.fetcher->channel())
632 << " to " << f.writer->filename() << " data "
633 << FlatbufferToJson(
634 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
635 fbb.GetBufferPointer()));
636
637 max_header_size_ = std::max(max_header_size_,
638 fbb.GetSize() - f.fetcher->context().size);
639 f.writer->QueueSizedFlatbuffer(&fbb);
640 }
641
642 if (f.timestamp_writer != nullptr) {
643 // And now handle timestamps.
644 const auto start = event_loop_->monotonic_now();
645 flatbuffers::FlatBufferBuilder fbb;
646 fbb.ForceDefaults(true);
647
648 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
649 f.channel_index,
650 LogType::kLogDeliveryTimeOnly));
651 const auto end = event_loop_->monotonic_now();
652 RecordCreateMessageTime(start, end, &f);
653
654 VLOG(2) << "Writing timestamps as node "
655 << FlatbufferToJson(event_loop_->node()) << " for channel "
656 << configuration::CleanedChannelToString(f.fetcher->channel())
657 << " to " << f.timestamp_writer->filename() << " timestamp "
658 << FlatbufferToJson(
659 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
660 fbb.GetBufferPointer()));
661
662 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
663 }
664
665 if (f.contents_writer != nullptr) {
666 const auto start = event_loop_->monotonic_now();
667 // And now handle the special message contents channel. Copy the
668 // message into a FlatBufferBuilder and save it to disk.
669 // TODO(austin): We can be more efficient here when we start to
670 // care...
671 flatbuffers::FlatBufferBuilder fbb;
672 fbb.ForceDefaults(true);
673
Austin Schuh0de30f32020-12-06 12:44:28 -0800674 const RemoteMessage *msg =
675 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700676
677 logger::MessageHeader::Builder message_header_builder(fbb);
678
679 // TODO(austin): This needs to check the channel_index and confirm
680 // that it should be logged before squirreling away the timestamp to
681 // disk. We don't want to log irrelevant timestamps.
682
683 // Note: this must match the same order as MessageBridgeServer and
684 // PackMessage. We want identical headers to have identical
685 // on-the-wire formats to make comparing them easier.
686
687 // Translate from the channel index that the event loop uses to the
688 // channel index in the log file.
689 message_header_builder.add_channel_index(
690 event_loop_to_logged_channel_index_[msg->channel_index()]);
691
692 message_header_builder.add_queue_index(msg->queue_index());
693 message_header_builder.add_monotonic_sent_time(
694 msg->monotonic_sent_time());
695 message_header_builder.add_realtime_sent_time(
696 msg->realtime_sent_time());
697
698 message_header_builder.add_monotonic_remote_time(
699 msg->monotonic_remote_time());
700 message_header_builder.add_realtime_remote_time(
701 msg->realtime_remote_time());
702 message_header_builder.add_remote_queue_index(
703 msg->remote_queue_index());
704
705 fbb.FinishSizePrefixed(message_header_builder.Finish());
706 const auto end = event_loop_->monotonic_now();
707 RecordCreateMessageTime(start, end, &f);
708
709 f.contents_writer->QueueSizedFlatbuffer(&fbb);
710 }
711
712 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700713 }
714 }
715 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800716}
717
Brian Silverman1f345222020-09-24 21:14:48 -0700718void Logger::DoLogData(const monotonic_clock::time_point end_time) {
719 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800720 // max_out_of_order_duration. To do this, we need sync points. Every write
721 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800722
723 do {
724 // Move the sync point up by at most polling_period. This forces one sync
725 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700726 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
727
728 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800729
Austin Schuhe309d2a2019-11-29 13:25:21 -0800730 // If we missed cycles, we could be pretty far behind. Spin until we are
731 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700732 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800733}
734
Brian Silvermancb805822020-10-06 17:43:35 -0700735void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
736 aos::monotonic_clock::time_point end,
737 bool got_new, FetcherStruct *fetcher) {
738 const auto duration = end - start;
739 if (!got_new) {
740 ++total_nop_fetch_count_;
741 total_nop_fetch_time_ += duration;
742 return;
743 }
744 ++total_message_fetch_count_;
745 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
746 total_message_fetch_time_ += duration;
747 if (duration > max_message_fetch_time_) {
748 max_message_fetch_time_ = duration;
749 max_message_fetch_time_channel_ = fetcher->channel_index;
750 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
751 }
752}
753
754void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
755 aos::monotonic_clock::time_point end,
756 FetcherStruct *fetcher) {
757 const auto duration = end - start;
758 total_copy_time_ += duration;
759 ++total_copy_count_;
760 total_copy_bytes_ += fetcher->fetcher->context().size;
761 if (duration > max_copy_time_) {
762 max_copy_time_ = duration;
763 max_copy_time_channel_ = fetcher->channel_index;
764 max_copy_time_size_ = fetcher->fetcher->context().size;
765 }
766}
767
Austin Schuh11d43732020-09-21 17:28:30 -0700768std::vector<std::vector<std::string>> ToLogReaderVector(
769 const std::vector<LogFile> &log_files) {
770 std::vector<std::vector<std::string>> result;
771 for (const LogFile &log_file : log_files) {
772 for (const LogParts &log_parts : log_file.parts) {
773 std::vector<std::string> parts;
774 for (const std::string &part : log_parts.parts) {
775 parts.emplace_back(part);
776 }
777 result.emplace_back(std::move(parts));
778 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700779 }
780 return result;
781}
782
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800783LogReader::LogReader(std::string_view filename,
784 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800785 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800786
Austin Schuh287d43d2020-12-04 20:19:33 -0800787LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800788 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800789 : log_files_(std::move(log_files)),
790 log_file_header_(MaybeReadHeaderOrDie(log_files_)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800791 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800792 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800793
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700794 // Remap all existing remote timestamp channels. They will be recreated, and
795 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700796 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700797 std::vector<const Node *> timestamp_logger_nodes =
798 configuration::TimestampNodes(logged_configuration(), node);
799 for (const Node *remote_node : timestamp_logger_nodes) {
800 const std::string channel = absl::StrCat(
801 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800802 // See if the log file is an old log with MessageHeader channels in it, or
803 // a newer log with RemoteMessage. If we find an older log, rename the
804 // type too along with the name.
805 if (HasChannel<MessageHeader>(channel, node)) {
806 CHECK(!HasChannel<RemoteMessage>(channel, node))
807 << ": Can't have both a MessageHeader and RemoteMessage remote "
808 "timestamp channel.";
809 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
810 "aos.message_bridge.RemoteMessage");
811 } else {
812 CHECK(HasChannel<RemoteMessage>(channel, node))
813 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
814 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
815 << node->name()->string_view();
816 RemapLoggedChannel<RemoteMessage>(channel, node);
817 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700818 }
819 }
820
Austin Schuh6aa77be2020-02-22 21:06:40 -0800821 if (replay_configuration) {
822 CHECK_EQ(configuration::MultiNode(configuration()),
823 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700824 << ": Log file and replay config need to both be multi or single "
825 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800826 }
827
Austin Schuh6f3babe2020-01-26 20:34:50 -0800828 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800829 states_.emplace_back(std::make_unique<State>(
830 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800831 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800832 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700833 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800834 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700835 << ": Log file and replay config need to have matching nodes "
836 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700837 for (const Node *node : *logged_configuration()->nodes()) {
838 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700839 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
840 << " in logged config that is not present in the replay "
841 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700842 }
843 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800844 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800845 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800846 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800847}
848
Austin Schuh6aa77be2020-02-22 21:06:40 -0800849LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700850 if (event_loop_factory_unique_ptr_) {
851 Deregister();
852 } else if (event_loop_factory_ != nullptr) {
853 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
854 "is destroyed";
855 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800856 if (offset_fp_ != nullptr) {
857 fclose(offset_fp_);
858 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700859 // Zero out some buffers. It's easy to do use-after-frees on these, so make
860 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700861 if (remapped_configuration_buffer_) {
862 remapped_configuration_buffer_->Wipe();
863 }
864 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -0800865}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800866
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800867const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800868 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800869}
870
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800871const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800872 return remapped_configuration_;
873}
874
Austin Schuh6f3babe2020-01-26 20:34:50 -0800875std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700876 // Because the Node pointer will only be valid if it actually points to
877 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800878 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800879 //
880 // Also, note, that when ever a map is changed, the nodes in here are
881 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800882 CHECK(remapped_configuration_ != nullptr)
883 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800884 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800885}
Austin Schuh15649d62019-12-28 16:36:38 -0800886
Austin Schuh11d43732020-09-21 17:28:30 -0700887monotonic_clock::time_point LogReader::monotonic_start_time(
888 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800889 State *state =
890 states_[configuration::GetNodeIndex(configuration(), node)].get();
891 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
892
Austin Schuh858c9f32020-08-31 16:56:12 -0700893 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800894}
895
Austin Schuh11d43732020-09-21 17:28:30 -0700896realtime_clock::time_point LogReader::realtime_start_time(
897 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800898 State *state =
899 states_[configuration::GetNodeIndex(configuration(), node)].get();
900 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
901
Austin Schuh858c9f32020-08-31 16:56:12 -0700902 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800903}
904
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800905void LogReader::Register() {
906 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800907 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800908 Register(event_loop_factory_unique_ptr_.get());
909}
910
Austin Schuh92547522019-12-28 14:33:43 -0800911void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800912 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700913 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -0800914
Brian Silvermand90905f2020-09-23 14:42:56 -0700915 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800916 const size_t node_index =
917 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -0800918 std::vector<LogParts> filtered_parts = FilterPartsForNode(
919 log_files_, node != nullptr ? node->name()->string_view() : "");
920 states_[node_index] = std::make_unique<State>(
921 filtered_parts.size() == 0u
922 ? nullptr
923 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800924 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700925 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700926 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700927
928 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -0800929 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700930
Austin Schuh287d43d2020-12-04 20:19:33 -0800931 for (const Node *node : configuration::GetNodes(configuration())) {
932 const size_t node_index =
933 configuration::GetNodeIndex(configuration(), node);
934 State *state = states_[node_index].get();
935 for (const Node *other_node : configuration::GetNodes(configuration())) {
936 const size_t other_node_index =
937 configuration::GetNodeIndex(configuration(), other_node);
938 State *other_state = states_[other_node_index].get();
939 if (other_state != state) {
940 state->AddPeer(other_state);
941 }
942 }
943 }
944
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700945 // Register after making all the State objects so we can build references
946 // between them.
947 for (const Node *node : configuration::GetNodes(configuration())) {
948 const size_t node_index =
949 configuration::GetNodeIndex(configuration(), node);
950 State *state = states_[node_index].get();
951
952 Register(state->event_loop());
953 }
954
James Kuszmaul46d82582020-05-09 19:50:09 -0700955 if (live_nodes_ == 0) {
956 LOG(FATAL)
957 << "Don't have logs from any of the nodes in the replay config--are "
958 "you sure that the replay config matches the original config?";
959 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800960
Austin Schuh2f8fd752020-09-01 22:38:28 -0700961 // We need to now seed our per-node time offsets and get everything set up
962 // to run.
963 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -0800964
Austin Schuh8bd96322020-02-13 21:18:22 -0800965 // It is easiest to solve for per node offsets with a matrix rather than
966 // trying to solve the equations by hand. So let's get after it.
967 //
968 // Now, build up the map matrix.
969 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700970 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
971 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
972 filters_.size() + 1, num_nodes);
973 slope_matrix_ =
974 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
975 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800976
Austin Schuh2f8fd752020-09-01 22:38:28 -0700977 offset_matrix_ =
978 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
979 valid_matrix_ =
980 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
981 last_valid_matrix_ =
982 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -0800983
Austin Schuh2f8fd752020-09-01 22:38:28 -0700984 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
985 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -0800986
Austin Schuh2f8fd752020-09-01 22:38:28 -0700987 // All times should average out to the distributed clock.
988 for (int i = 0; i < map_matrix_.cols(); ++i) {
989 // 1/num_nodes.
990 map_matrix_(0, i) = mpq_class(1, num_nodes);
991 }
992 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800993
994 {
995 // Now, add the a - b -> sample elements.
996 size_t i = 1;
997 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700998 std::tuple<message_bridge::NoncausalOffsetEstimator>>
999 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001000 const Node *const node_a = std::get<0>(filter.first);
1001 const Node *const node_b = std::get<1>(filter.first);
1002
1003 const size_t node_a_index =
1004 configuration::GetNodeIndex(configuration(), node_a);
1005 const size_t node_b_index =
1006 configuration::GetNodeIndex(configuration(), node_b);
1007
Austin Schuh2f8fd752020-09-01 22:38:28 -07001008 // -a
1009 map_matrix_(i, node_a_index) = mpq_class(-1);
1010 // +b
1011 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -08001012
1013 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -07001014 std::get<0>(filter.second)
1015 .set_slope_pointer(&slope_matrix_(i, node_a_index));
1016 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
1017
1018 valid_matrix_(i) = false;
1019 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -08001020
1021 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001022 }
1023 }
1024
Austin Schuh858c9f32020-08-31 16:56:12 -07001025 for (std::unique_ptr<State> &state : states_) {
1026 state->SeedSortedMessages();
1027 }
1028
Austin Schuh2f8fd752020-09-01 22:38:28 -07001029 // Rank of the map matrix tells you if all the nodes are in communication
1030 // with each other, which tells you if the offsets are observable.
1031 const size_t connected_nodes =
1032 Eigen::FullPivLU<
1033 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
1034 .rank();
1035
1036 // We don't need to support isolated nodes until someone has a real use
1037 // case.
1038 CHECK_EQ(connected_nodes, num_nodes)
1039 << ": There is a node which isn't communicating with the rest.";
1040
1041 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001042 UpdateOffsets();
1043
Austin Schuh2f8fd752020-09-01 22:38:28 -07001044 // We want to start the log file at the last start time of the log files
1045 // from all the nodes. Compute how long each node's simulation needs to run
1046 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001047 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001048
Austin Schuh2f8fd752020-09-01 22:38:28 -07001049 // TODO(austin): We want an "OnStart" callback for each node rather than
1050 // running until the last node.
1051
Austin Schuh8bd96322020-02-13 21:18:22 -08001052 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001053 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1054 << MaybeNodeName(state->event_loop()->node()) << "now "
1055 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001056 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1057 continue;
1058 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001059 // And start computing the start time on the distributed clock now that
1060 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001061 start_time = std::max(
1062 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001063 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064
1065 CHECK_GE(start_time, distributed_clock::epoch())
1066 << ": Hmm, we have a node starting before the start of time. Offset "
1067 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001068
Austin Schuh6f3babe2020-01-26 20:34:50 -08001069 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1070 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001071 // nodes, and also replayed on the other nodes. This may not satisfy all
1072 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001073 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1074 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1075 const Channel *channel = logged_configuration()->channels()->Get(i);
1076 const Node *node = configuration::GetNode(
1077 configuration(), channel->source_node()->string_view());
1078
Austin Schuh8bd96322020-02-13 21:18:22 -08001079 State *state =
1080 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001081
1082 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001083 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001084
1085 event_loop_factory_->DisableForwarding(remapped_channel);
1086 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001087
1088 // If we are replaying a log, we don't want a bunch of redundant messages
1089 // from both the real message bridge and simulated message bridge.
1090 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001091 }
1092
Austin Schuhcde938c2020-02-02 17:30:07 -08001093 // While we are starting the system up, we might be relying on matching data
1094 // to timestamps on log files where the timestamp log file starts before the
1095 // data. In this case, it is reasonable to expect missing data.
1096 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001097 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001098 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001099 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001100 // Now that we are running for real, missing data means that the log file is
1101 // corrupted or went wrong.
1102 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001103
Austin Schuh8bd96322020-02-13 21:18:22 -08001104 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001105 // Make the RT clock be correct before handing it to the user.
1106 if (state->realtime_start_time() != realtime_clock::min_time) {
1107 state->SetRealtimeOffset(state->monotonic_start_time(),
1108 state->realtime_start_time());
1109 }
1110 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1111 << MaybeNodeName(state->event_loop()->node()) << "now "
1112 << state->monotonic_now();
1113 }
1114
1115 if (FLAGS_timestamps_to_csv) {
1116 for (std::pair<const std::tuple<const Node *, const Node *>,
1117 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1118 &filter : filters_) {
1119 const Node *const node_a = std::get<0>(filter.first);
1120 const Node *const node_b = std::get<1>(filter.first);
1121
1122 std::get<0>(filter.second)
1123 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1124 ->monotonic_now());
1125 std::get<0>(filter.second)
1126 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1127 ->monotonic_now());
1128 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001129 }
1130}
1131
Austin Schuh2f8fd752020-09-01 22:38:28 -07001132void LogReader::UpdateOffsets() {
1133 VLOG(2) << "Samples are " << offset_matrix_;
1134 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1135 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1136 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1137 "]");
1138 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1139 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1140
1141 size_t node_index = 0;
1142 for (std::unique_ptr<State> &state : states_) {
1143 state->SetDistributedOffset(offset(node_index), slope(node_index));
1144 VLOG(1) << "Offset for node " << node_index << " "
1145 << MaybeNodeName(state->event_loop()->node()) << "is "
1146 << aos::distributed_clock::time_point(offset(node_index))
1147 << " slope " << std::setprecision(9) << std::fixed
1148 << slope(node_index);
1149 ++node_index;
1150 }
1151
1152 if (VLOG_IS_ON(1)) {
1153 LogFit("Offset is");
1154 }
1155}
1156
1157void LogReader::LogFit(std::string_view prefix) {
1158 for (std::unique_ptr<State> &state : states_) {
1159 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1160 << state->monotonic_now() << " distributed "
1161 << event_loop_factory_->distributed_now();
1162 }
1163
1164 for (std::pair<const std::tuple<const Node *, const Node *>,
1165 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1166 filters_) {
1167 message_bridge::NoncausalOffsetEstimator *estimator =
1168 &std::get<0>(filter.second);
1169
1170 if (estimator->a_timestamps().size() == 0 &&
1171 estimator->b_timestamps().size() == 0) {
1172 continue;
1173 }
1174
1175 if (VLOG_IS_ON(1)) {
1176 estimator->LogFit(prefix);
1177 }
1178
1179 const Node *const node_a = std::get<0>(filter.first);
1180 const Node *const node_b = std::get<1>(filter.first);
1181
1182 const size_t node_a_index =
1183 configuration::GetNodeIndex(configuration(), node_a);
1184 const size_t node_b_index =
1185 configuration::GetNodeIndex(configuration(), node_b);
1186
1187 const double recovered_slope =
1188 slope(node_b_index) / slope(node_a_index) - 1.0;
1189 const int64_t recovered_offset =
1190 offset(node_b_index).count() - offset(node_a_index).count() *
1191 slope(node_b_index) /
1192 slope(node_a_index);
1193
1194 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1195 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1196 << " offset " << std::setprecision(20) << recovered_offset
1197 << " (error "
1198 << recovered_offset - estimator->fit().offset().count() << ")";
1199
1200 const aos::distributed_clock::time_point a0 =
1201 states_[node_a_index]->ToDistributedClock(
1202 std::get<0>(estimator->a_timestamps()[0]));
1203 const aos::distributed_clock::time_point a1 =
1204 states_[node_a_index]->ToDistributedClock(
1205 std::get<0>(estimator->a_timestamps()[1]));
1206
1207 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1208 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1209 << " distributed -> " << node_b->name()->string_view() << " "
1210 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1211 << aos::monotonic_clock::time_point(
1212 std::chrono::nanoseconds(static_cast<int64_t>(
1213 std::get<0>(estimator->a_timestamps()[0])
1214 .time_since_epoch()
1215 .count() *
1216 (1.0 + estimator->fit().slope()))) +
1217 estimator->fit().offset())
1218 << ((a0 <= event_loop_factory_->distributed_now())
1219 ? ""
1220 : " After now, investigate");
1221 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1222 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1223 << " distributed -> " << node_b->name()->string_view() << " "
1224 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1225 << aos::monotonic_clock::time_point(
1226 std::chrono::nanoseconds(static_cast<int64_t>(
1227 std::get<0>(estimator->a_timestamps()[1])
1228 .time_since_epoch()
1229 .count() *
1230 (1.0 + estimator->fit().slope()))) +
1231 estimator->fit().offset())
1232 << ((event_loop_factory_->distributed_now() <= a1)
1233 ? ""
1234 : " Before now, investigate");
1235
1236 const aos::distributed_clock::time_point b0 =
1237 states_[node_b_index]->ToDistributedClock(
1238 std::get<0>(estimator->b_timestamps()[0]));
1239 const aos::distributed_clock::time_point b1 =
1240 states_[node_b_index]->ToDistributedClock(
1241 std::get<0>(estimator->b_timestamps()[1]));
1242
1243 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1244 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1245 << " distributed -> " << node_a->name()->string_view() << " "
1246 << states_[node_a_index]->FromDistributedClock(b0)
1247 << ((b0 <= event_loop_factory_->distributed_now())
1248 ? ""
1249 : " After now, investigate");
1250 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1251 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1252 << " distributed -> " << node_a->name()->string_view() << " "
1253 << states_[node_a_index]->FromDistributedClock(b1)
1254 << ((event_loop_factory_->distributed_now() <= b1)
1255 ? ""
1256 : " Before now, investigate");
1257 }
1258}
1259
1260message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001261 const Node *node_a, const Node *node_b) {
1262 CHECK_NE(node_a, node_b);
1263 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1264 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1265
1266 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001267 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001268 }
1269
1270 auto tuple = std::make_tuple(node_a, node_b);
1271
1272 auto it = filters_.find(tuple);
1273
1274 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001275 auto &x =
1276 filters_
1277 .insert(std::make_pair(
1278 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1279 node_a, node_b))))
1280 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001281 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001282 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1283 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1284 node_b->name()->string_view()));
1285 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1286 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1287 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001288 }
1289
Austin Schuh2f8fd752020-09-01 22:38:28 -07001290 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001291 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001292 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001293 }
1294}
1295
Austin Schuhe309d2a2019-11-29 13:25:21 -08001296void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001297 State *state =
1298 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1299 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001300
Austin Schuh858c9f32020-08-31 16:56:12 -07001301 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001302
Tyler Chatow67ddb032020-01-12 14:30:04 -08001303 // We don't run timing reports when trying to print out logged data, because
1304 // otherwise we would end up printing out the timing reports themselves...
1305 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001306 event_loop->SkipTimingReport();
1307 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001308
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001309 for (size_t logged_channel_index = 0;
1310 logged_channel_index < logged_configuration()->channels()->size();
1311 ++logged_channel_index) {
1312 const Channel *channel = RemapChannel(
1313 event_loop,
1314 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001315
Austin Schuh2f8fd752020-09-01 22:38:28 -07001316 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001317 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001318
1319 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001320
1321 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1322 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001323 // We've got a message which is being forwarded to this node.
1324 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001325 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001326 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001327
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001328 // Delivery timestamps are supposed to be logged back on the source node.
1329 // Configure remote timestamps to be sent.
1330 const bool delivery_time_is_logged =
1331 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1332 channel, event_loop->node(), source_node);
1333
1334 source_state =
1335 states_[configuration::GetNodeIndex(configuration(), source_node)]
1336 .get();
1337
1338 if (delivery_time_is_logged) {
1339 remote_timestamp_sender =
1340 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001341 }
1342 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001343
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001344 state->SetChannel(
1345 logged_channel_index,
1346 configuration::ChannelIndex(event_loop->configuration(), channel),
1347 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1348 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001349 }
1350
Austin Schuh6aa77be2020-02-22 21:06:40 -08001351 // If we didn't find any log files with data in them, we won't ever get a
1352 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001353 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001354 return;
1355 }
1356
Austin Schuh858c9f32020-08-31 16:56:12 -07001357 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001358 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1359 << "at " << state->event_loop()->context().monotonic_event_time
1360 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001361 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001362 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001363 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001364 if (live_nodes_ == 0) {
1365 event_loop_factory_->Exit();
1366 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001367 return;
1368 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001369 if (VLOG_IS_ON(1)) {
1370 LogFit("Offset was");
1371 }
1372
1373 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001374 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001375
Austin Schuhe309d2a2019-11-29 13:25:21 -08001376 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001377 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001379 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001380 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1381 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001382 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001383 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001384 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001385 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001386 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001387 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001388 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001389 << "): " << FlatbufferToJson(state->event_loop()->node())
1390 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001391 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001392 << state->DebugString();
1393 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001394
Austin Schuh287d43d2020-12-04 20:19:33 -08001395 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001396 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001397 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001398 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001399 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001400 timestamped_message.data.span().size() != 0u) {
1401 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001402 << ": Got a message without data on channel "
1403 << configuration::CleanedChannelToString(
1404 logged_configuration()->channels()->Get(
1405 timestamped_message.channel_index))
1406 << ". Forwarding entry which was not matched? Use "
1407 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001408
Austin Schuh2f8fd752020-09-01 22:38:28 -07001409 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001410 // Confirm that the message was sent on the sending node before the
1411 // destination node (this node). As a proxy, do this by making sure
1412 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001413 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001414 CHECK_LT(
1415 timestamped_message.monotonic_remote_time,
1416 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001417 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001418 << state->remote_node(timestamped_message.channel_index)
1419 ->name()
1420 ->string_view()
Austin Schuh2f8fd752020-09-01 22:38:28 -07001421 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001422 } else if (timestamped_message.monotonic_remote_time >=
1423 state->monotonic_remote_now(
1424 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001425 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001426 << "Check failed: timestamped_message.monotonic_remote_time < "
1427 "state->monotonic_remote_now(timestamped_message.channel_"
1428 "index) ("
1429 << timestamped_message.monotonic_remote_time << " vs. "
1430 << state->monotonic_remote_now(
1431 timestamped_message.channel_index)
1432 << ") " << state->event_loop()->node()->name()->string_view()
1433 << " to "
1434 << state->remote_node(timestamped_message.channel_index)
1435 ->name()
1436 ->string_view()
1437 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001438 << " ("
1439 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001440 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001441 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001442 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001443 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001444 timestamped_message.channel_index,
1445 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001446 << ") " << state->DebugString();
1447 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001448
1449 if (FLAGS_timestamps_to_csv) {
1450 if (offset_fp_ == nullptr) {
1451 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1452 fprintf(
1453 offset_fp_,
1454 "# time_since_start, offset node 0, offset node 1, ...\n");
Austin Schuh287d43d2020-12-04 20:19:33 -08001455 first_time_ = timestamped_message.realtime_event_time;
Austin Schuh8bd96322020-02-13 21:18:22 -08001456 }
1457
1458 fprintf(offset_fp_, "%.9f",
1459 std::chrono::duration_cast<std::chrono::duration<double>>(
Austin Schuh287d43d2020-12-04 20:19:33 -08001460 timestamped_message.realtime_event_time - first_time_)
Austin Schuh8bd96322020-02-13 21:18:22 -08001461 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001462 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1463 fprintf(offset_fp_, ", %.9f",
1464 time_offset_matrix_(i, 0) +
1465 time_slope_matrix_(i, 0) *
1466 chrono::duration<double>(
1467 event_loop_factory_->distributed_now()
1468 .time_since_epoch())
1469 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001470 }
1471 fprintf(offset_fp_, "\n");
1472 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001473 }
1474
Austin Schuh15649d62019-12-28 16:36:38 -08001475 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001476 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1477 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001478
Austin Schuh2f8fd752020-09-01 22:38:28 -07001479 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001480 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001481 // TODO(austin): std::move channel_data in and make that efficient in
1482 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001483 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001484 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001485 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001486 // reading the rest of the log file and call it quits. We don't want
1487 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001488 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1489 bool update_time_dummy;
1490 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001491 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001492 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001493 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001494 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001495 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001496 LOG(WARNING)
1497 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001498 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001499 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001500 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001501 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001502 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001503 }
1504
Austin Schuh858c9f32020-08-31 16:56:12 -07001505 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001506 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001507 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1508 << "wakeup for " << next_time << "("
1509 << state->ToDistributedClock(next_time)
1510 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001511 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001512 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001513 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1514 << "No next message, scheduling shutdown";
1515 // Set a timer up immediately after now to die. If we don't do this,
1516 // then the senders waiting on the message we just read will never get
1517 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001518 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001519 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1520 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001521 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001522 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001523
Austin Schuh2f8fd752020-09-01 22:38:28 -07001524 // Once we make this call, the current time changes. So do everything
1525 // which involves time before changing it. That especially includes
1526 // sending the message.
1527 if (update_time) {
1528 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1529 << "updating offsets";
1530
1531 std::vector<aos::monotonic_clock::time_point> before_times;
1532 before_times.resize(states_.size());
1533 std::transform(states_.begin(), states_.end(), before_times.begin(),
1534 [](const std::unique_ptr<State> &state) {
1535 return state->monotonic_now();
1536 });
1537
1538 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001539 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1540 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001541 }
1542
Austin Schuh8bd96322020-02-13 21:18:22 -08001543 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001544 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1545 << state->monotonic_now();
1546
1547 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001548 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1549 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001550 }
1551
1552 // TODO(austin): We should be perfect.
1553 const std::chrono::nanoseconds kTolerance{3};
1554 if (!FLAGS_skip_order_validation) {
1555 CHECK_GE(next_time, state->monotonic_now())
1556 << ": Time skipped the next event.";
1557
1558 for (size_t i = 0; i < states_.size(); ++i) {
1559 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1560 << ": Time changed too much on node "
1561 << MaybeNodeName(states_[i]->event_loop()->node());
1562 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1563 << ": Time changed too much on node "
1564 << states_[i]->event_loop()->node()->name()->string_view();
1565 }
1566 } else {
1567 if (next_time < state->monotonic_now()) {
1568 LOG(WARNING) << "Check failed: next_time >= "
1569 "state->monotonic_now() ("
1570 << next_time << " vs. " << state->monotonic_now()
1571 << "): Time skipped the next event.";
1572 }
1573 for (size_t i = 0; i < states_.size(); ++i) {
1574 if (states_[i]->monotonic_now() >= before_times[i] - kTolerance) {
1575 LOG(WARNING) << "Check failed: "
1576 "states_[i]->monotonic_now() "
1577 ">= before_times[i] - kTolerance ("
1578 << states_[i]->monotonic_now() << " vs. "
1579 << before_times[i] - kTolerance
1580 << ") : Time changed too much on node "
1581 << MaybeNodeName(states_[i]->event_loop()->node());
1582 }
1583 if (states_[i]->monotonic_now() <= before_times[i] + kTolerance) {
1584 LOG(WARNING) << "Check failed: "
1585 "states_[i]->monotonic_now() "
1586 "<= before_times[i] + kTolerance ("
1587 << states_[i]->monotonic_now() << " vs. "
1588 << before_times[i] - kTolerance
1589 << ") : Time changed too much on node "
1590 << MaybeNodeName(states_[i]->event_loop()->node());
1591 }
1592 }
1593 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001594 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001595
1596 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1597 << state->event_loop()->context().monotonic_event_time << " now "
1598 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001599 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001600
Austin Schuh6f3babe2020-01-26 20:34:50 -08001601 ++live_nodes_;
1602
Austin Schuh858c9f32020-08-31 16:56:12 -07001603 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1604 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001605 }
1606}
1607
1608void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001609 // Make sure that things get destroyed in the correct order, rather than
1610 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001611 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001612 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001613 }
Austin Schuh92547522019-12-28 14:33:43 -08001614
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001615 event_loop_factory_unique_ptr_.reset();
1616 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001617}
1618
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001619void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001620 std::string_view add_prefix,
1621 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001622 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1623 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1624 if (channel->name()->str() == name &&
1625 channel->type()->string_view() == type) {
1626 CHECK_EQ(0u, remapped_channels_.count(ii))
1627 << "Already remapped channel "
1628 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001629 RemappedChannel remapped_channel;
1630 remapped_channel.remapped_name =
1631 std::string(add_prefix) + std::string(name);
1632 remapped_channel.new_type = new_type;
1633 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001634 VLOG(1) << "Remapping channel "
1635 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001636 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001637 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001638 return;
1639 }
1640 }
1641 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1642 << type;
1643}
1644
Austin Schuh01b4c352020-09-21 23:09:39 -07001645void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1646 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001647 std::string_view add_prefix,
1648 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001649 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1650 const Channel *remapped_channel =
1651 configuration::GetChannel(logged_configuration(), name, type, "", node);
1652 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1653 << "\", \"type\": \"" << type << "\"}";
1654 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1655 << "\"}";
1656 VLOG(1) << "Remapped "
1657 << aos::configuration::StrippedChannelToString(remapped_channel);
1658
1659 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1660 // we want it to degrade if the heuristics fail to just work.
1661 //
1662 // The easiest way to do this is going to be incredibly specific and verbose.
1663 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1664 // /original/0/spray. Then, create a map from /original/spray to
1665 // /original/0/spray for just the type we were asked for.
1666 if (name != remapped_channel->name()->string_view()) {
1667 MapT new_map;
1668 new_map.match = std::make_unique<ChannelT>();
1669 new_map.match->name = absl::StrCat(add_prefix, name);
1670 new_map.match->type = type;
1671 if (node != nullptr) {
1672 new_map.match->source_node = node->name()->str();
1673 }
1674 new_map.rename = std::make_unique<ChannelT>();
1675 new_map.rename->name =
1676 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1677 maps_.emplace_back(std::move(new_map));
1678 }
1679
1680 const size_t channel_index =
1681 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1682 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1683 << "Already remapped channel "
1684 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001685
1686 RemappedChannel remapped_channel_struct;
1687 remapped_channel_struct.remapped_name =
1688 std::string(add_prefix) +
1689 std::string(remapped_channel->name()->string_view());
1690 remapped_channel_struct.new_type = new_type;
1691 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001692 MakeRemappedConfig();
1693}
1694
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001695void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001696 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001697 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001698 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001699 << ": Can't change the mapping after the events are scheduled.";
1700 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001701 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001702
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001703 // If no remapping occurred and we are using the original config, then there
1704 // is nothing interesting to do here.
1705 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001706 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001707 return;
1708 }
1709 // Config to copy Channel definitions from. Use the specified
1710 // replay_configuration_ if it has been provided.
1711 const Configuration *const base_config = replay_configuration_ == nullptr
1712 ? logged_configuration()
1713 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001714
1715 // Create a config with all the channels, but un-sorted/merged. Collect up
1716 // the schemas while we do this. Call MergeConfiguration to sort everything,
1717 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001718
1719 // This is the builder that we use for the config containing all the new
1720 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001721 flatbuffers::FlatBufferBuilder fbb;
1722 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001723 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001724
1725 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1726 << ": Merging logic needs to be updated when the number of channel "
1727 "fields changes.";
1728
1729 // List of schemas.
1730 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1731 // Make sure our new RemoteMessage schema is in there for old logs without it.
1732 schema_map.insert(std::make_pair(
1733 RemoteMessage::GetFullyQualifiedName(),
1734 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1735 message_bridge::RemoteMessageSchema()))));
1736
1737 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001738 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001739 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001740 base_config, logged_configuration()->channels()->Get(pair.first), "",
1741 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001742 channel_offsets.emplace_back(
1743 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001744 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001745
Austin Schuh0de30f32020-12-06 12:44:28 -08001746 // Now reconstruct the original channels, translating types as needed
1747 for (const Channel *c : *base_config->channels()) {
1748 // Search for a mapping channel.
1749 std::string_view new_type = "";
1750 for (auto &pair : remapped_channels_) {
1751 const Channel *const remapped_channel =
1752 logged_configuration()->channels()->Get(pair.first);
1753 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1754 remapped_channel->type()->string_view() == c->type()->string_view()) {
1755 new_type = pair.second.new_type;
1756 break;
1757 }
1758 }
1759
1760 // Copy everything over.
1761 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1762
1763 // Add the schema if it doesn't exist.
1764 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1765 CHECK(c->has_schema());
1766 schema_map.insert(std::make_pair(c->type()->string_view(),
1767 RecursiveCopyFlatBuffer(c->schema())));
1768 }
1769 }
1770
1771 // The MergeConfiguration API takes a vector, not a map. Convert.
1772 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1773 while (!schema_map.empty()) {
1774 schemas.emplace_back(std::move(schema_map.begin()->second));
1775 schema_map.erase(schema_map.begin());
1776 }
1777
1778 // Create the Configuration containing the new channels that we want to add.
1779 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1780 channels_offset =
1781 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1782
1783 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001784 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001785 if (base_config->maps()) {
1786 for (const Map *map : *base_config->maps()) {
1787 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1788 }
1789 }
1790
1791 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001792 for (const MapT &map : maps_) {
1793 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001794 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001795 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001796 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001797 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001798 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001799 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1800 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001801 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001802 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001803 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001804 match_builder.add_name(match_name_offset);
1805 match_builder.add_type(match_type_offset);
1806 if (!map.match->source_node.empty()) {
1807 match_builder.add_source_node(match_source_node_offset);
1808 }
1809 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1810
Austin Schuh0de30f32020-12-06 12:44:28 -08001811 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001812 rename_builder.add_name(rename_name_offset);
1813 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1814
Austin Schuh0de30f32020-12-06 12:44:28 -08001815 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001816 map_builder.add_match(match_offset);
1817 map_builder.add_rename(rename_offset);
1818 map_offsets.emplace_back(map_builder.Finish());
1819 }
1820
Austin Schuh0de30f32020-12-06 12:44:28 -08001821 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1822 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001823
Austin Schuh0de30f32020-12-06 12:44:28 -08001824 // And copy everything else over.
1825 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1826 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1827
1828 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1829 applications_offset =
1830 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1831
1832 // Now insert everything else in unmodified.
1833 ConfigurationBuilder configuration_builder(fbb);
1834 if (!channels_offset.IsNull()) {
1835 configuration_builder.add_channels(channels_offset);
1836 }
1837 if (!maps_offsets.IsNull()) {
1838 configuration_builder.add_maps(maps_offsets);
1839 }
1840 if (!nodes_offset.IsNull()) {
1841 configuration_builder.add_nodes(nodes_offset);
1842 }
1843 if (!applications_offset.IsNull()) {
1844 configuration_builder.add_applications(applications_offset);
1845 }
1846
1847 if (base_config->has_channel_storage_duration()) {
1848 configuration_builder.add_channel_storage_duration(
1849 base_config->channel_storage_duration());
1850 }
1851
1852 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1853 << ": Merging logic needs to be updated when the number of configuration "
1854 "fields changes.";
1855
1856 fbb.Finish(configuration_builder.Finish());
1857
1858 // Clean it up and return it! By using MergeConfiguration here, we'll
1859 // actually get a deduplicated config for free too.
1860 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1861 configuration::MergeConfiguration(
1862 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1863
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001864 remapped_configuration_buffer_ =
1865 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001866 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001867
1868 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001869
1870 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001871}
1872
Austin Schuh6f3babe2020-01-26 20:34:50 -08001873const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1874 const Channel *channel) {
1875 std::string_view channel_name = channel->name()->string_view();
1876 std::string_view channel_type = channel->type()->string_view();
1877 const int channel_index =
1878 configuration::ChannelIndex(logged_configuration(), channel);
1879 // If the channel is remapped, find the correct channel name to use.
1880 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001881 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001882 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001883 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001884 }
1885
Austin Schuhee711052020-08-24 16:06:09 -07001886 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001887 const Channel *remapped_channel = configuration::GetChannel(
1888 event_loop->configuration(), channel_name, channel_type,
1889 event_loop->name(), event_loop->node());
1890
1891 CHECK(remapped_channel != nullptr)
1892 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1893 << channel_type << "\"} because it is not in the provided configuration.";
1894
1895 return remapped_channel;
1896}
1897
Austin Schuh287d43d2020-12-04 20:19:33 -08001898LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1899 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1900
1901void LogReader::State::AddPeer(State *peer) {
1902 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1903 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1904 }
1905}
Austin Schuh858c9f32020-08-31 16:56:12 -07001906
1907EventLoop *LogReader::State::SetNodeEventLoopFactory(
1908 NodeEventLoopFactory *node_event_loop_factory) {
1909 node_event_loop_factory_ = node_event_loop_factory;
1910 event_loop_unique_ptr_ =
1911 node_event_loop_factory_->MakeEventLoop("log_reader");
1912 return event_loop_unique_ptr_.get();
1913}
1914
1915void LogReader::State::SetChannelCount(size_t count) {
1916 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001917 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001918 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001919 channel_source_state_.resize(count);
1920 factory_channel_index_.resize(count);
1921 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001922}
1923
1924void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001925 size_t logged_channel_index, size_t factory_channel_index,
1926 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001927 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08001928 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 channels_[logged_channel_index] = std::move(sender);
1930 filters_[logged_channel_index] = filter;
1931 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1932
1933 if (source_state) {
1934 channel_source_state_[logged_channel_index] = source_state;
1935
1936 if (remote_timestamp_sender != nullptr) {
1937 source_state->queue_index_map_[logged_channel_index] =
1938 std::make_unique<std::vector<State::SentTimestamp>>();
1939 }
1940 }
1941
1942 factory_channel_index_[logged_channel_index] = factory_channel_index;
1943}
1944
Austin Schuh287d43d2020-12-04 20:19:33 -08001945bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1946 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001947 uint32_t remote_queue_index = 0xffffffff;
1948
Austin Schuh287d43d2020-12-04 20:19:33 -08001949 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
1950 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
1951 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1952 ->queue_index_map_[timestamped_message.channel_index]
1953 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001954
1955 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08001956 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
1957 search.realtime_event_time = timestamped_message.realtime_remote_time;
1958 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001959
1960 // Find the sent time if available.
1961 auto element = std::lower_bound(
1962 queue_index_map->begin(), queue_index_map->end(), search,
1963 [](SentTimestamp a, SentTimestamp b) {
1964 if (b.monotonic_event_time < a.monotonic_event_time) {
1965 return false;
1966 }
1967 if (b.monotonic_event_time > a.monotonic_event_time) {
1968 return true;
1969 }
1970
1971 if (b.queue_index < a.queue_index) {
1972 return false;
1973 }
1974 if (b.queue_index > a.queue_index) {
1975 return true;
1976 }
1977
1978 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1979 return false;
1980 });
1981
1982 // TODO(austin): Be a bit more principled here, but we will want to do that
1983 // after the logger rewrite. We hit this when one node finishes, but the
1984 // other node isn't done yet. So there is no send time, but there is a
1985 // receive time.
1986 if (element != queue_index_map->end()) {
1987 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001988 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001989 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001990 timestamped_message.realtime_remote_time);
1991 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001992
1993 remote_queue_index = element->actual_queue_index;
1994 }
1995 }
1996
1997 // Send! Use the replayed queue index here instead of the logged queue index
1998 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001999 const bool sent = sender->Send(
2000 timestamped_message.data.message().data()->Data(),
2001 timestamped_message.data.message().data()->size(),
2002 timestamped_message.monotonic_remote_time,
2003 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002004 if (!sent) return false;
2005
Austin Schuh287d43d2020-12-04 20:19:33 -08002006 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002007 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08002008 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
2009 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
2010 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002011 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08002012 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2013 timestamp);
2014 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2015 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08002016 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08002017 remote_timestamp_senders_[timestamped_message.channel_index]
2018 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002019
Austin Schuh0de30f32020-12-06 12:44:28 -08002020 RemoteMessage::Builder message_header_builder =
2021 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002022
2023 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002024 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002025
2026 // Swap the remote and sent metrics. They are from the sender's
2027 // perspective, not the receiver's perspective.
2028 message_header_builder.add_monotonic_sent_time(
2029 sender->monotonic_sent_time().time_since_epoch().count());
2030 message_header_builder.add_realtime_sent_time(
2031 sender->realtime_sent_time().time_since_epoch().count());
2032 message_header_builder.add_queue_index(sender->sent_queue_index());
2033
2034 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002035 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002036 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002037 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002038
2039 message_header_builder.add_remote_queue_index(remote_queue_index);
2040
2041 builder.Send(message_header_builder.Finish());
2042 }
2043
2044 return true;
2045}
2046
Austin Schuh0de30f32020-12-06 12:44:28 -08002047aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002048 const Node *delivered_node) {
2049 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2050
2051 if (sender == remote_timestamp_senders_map_.end()) {
2052 sender = remote_timestamp_senders_map_
2053 .emplace(std::make_pair(
2054 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08002055 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002056 absl::StrCat("/aos/remote_timestamps/",
2057 delivered_node->name()->string_view()))))
2058 .first;
2059 }
2060
2061 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07002062}
2063
Austin Schuh287d43d2020-12-04 20:19:33 -08002064TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002065 CHECK_GT(sorted_messages_.size(), 0u);
2066
Austin Schuh287d43d2020-12-04 20:19:33 -08002067 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002068 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002069 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002070 << std::get<0>(result).monotonic_event_time;
2071 sorted_messages_.pop_front();
2072 SeedSortedMessages();
2073
Austin Schuh287d43d2020-12-04 20:19:33 -08002074 if (std::get<1>(result) != nullptr) {
2075 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002076 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2077 } else {
2078 *update_time = false;
2079 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002080 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002081}
2082
2083monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2084 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002085 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002086 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2087 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2088 }
2089
Austin Schuh287d43d2020-12-04 20:19:33 -08002090 TimestampedMessage *m =
2091 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2092 if (m == nullptr) {
2093 return monotonic_clock::max_time;
2094 }
2095 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002096}
2097
2098void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002099 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002100 const aos::monotonic_clock::time_point end_queue_time =
2101 (sorted_messages_.size() > 0
2102 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002103 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuh858c9f32020-08-31 16:56:12 -07002104 std::chrono::seconds(2);
2105
2106 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002107 TimestampedMessage *m = timestamp_mapper_->Front();
2108 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002109 return;
2110 }
2111 if (sorted_messages_.size() > 0) {
2112 // Stop placing sorted messages on the list once we have 2 seconds
2113 // queued up (but queue at least until the log starts.
2114 if (end_queue_time <
2115 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2116 return;
2117 }
2118 }
2119
Austin Schuh2f8fd752020-09-01 22:38:28 -07002120 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2121
Austin Schuh287d43d2020-12-04 20:19:33 -08002122 TimestampedMessage timestamped_message = std::move(*m);
2123 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002124
Austin Schuh2f8fd752020-09-01 22:38:28 -07002125 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002126 if (timestamped_message.monotonic_remote_time !=
2127 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002128 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002129 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002130
2131 CHECK(filter != nullptr);
2132
2133 // Call the correct method depending on if we are the forward or
2134 // reverse direction here.
2135 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002136 timestamped_message.monotonic_event_time,
2137 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002138 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002139 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002140 }
2141}
2142
2143void LogReader::State::Deregister() {
2144 for (size_t i = 0; i < channels_.size(); ++i) {
2145 channels_[i].reset();
2146 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002147 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002148 event_loop_unique_ptr_.reset();
2149 event_loop_ = nullptr;
2150 timer_handler_ = nullptr;
2151 node_event_loop_factory_ = nullptr;
2152}
2153
Austin Schuhe309d2a2019-11-29 13:25:21 -08002154} // namespace logger
2155} // namespace aos