blob: 654c7ced2ed4b4525f718055f8022073e117f53d [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
Austin Schuh315b96b2020-12-11 21:21:12 -080053std::string LogFileVectorToString(std::vector<LogFile> log_files) {
54 std::stringstream ss;
55 for (const auto f : log_files) {
56 ss << f << "\n";
57 }
58 return ss.str();
59}
60
Austin Schuh0de30f32020-12-06 12:44:28 -080061// Copies the channel, removing the schema as we go. If new_name is provided,
62// it is used instead of the name inside the channel. If new_type is provided,
63// it is used instead of the type in the channel.
64flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
65 std::string_view new_name,
66 std::string_view new_type,
67 flatbuffers::FlatBufferBuilder *fbb) {
68 flatbuffers::Offset<flatbuffers::String> name_offset =
69 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
70 : new_name);
71 flatbuffers::Offset<flatbuffers::String> type_offset =
72 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
73 flatbuffers::Offset<flatbuffers::String> source_node_offset =
74 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
75 : 0;
76
77 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
78 destination_nodes_offset =
79 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
80
81 flatbuffers::Offset<
82 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
83 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
84
85 Channel::Builder channel_builder(*fbb);
86 channel_builder.add_name(name_offset);
87 channel_builder.add_type(type_offset);
88 if (c->has_frequency()) {
89 channel_builder.add_frequency(c->frequency());
90 }
91 if (c->has_max_size()) {
92 channel_builder.add_max_size(c->max_size());
93 }
94 if (c->has_num_senders()) {
95 channel_builder.add_num_senders(c->num_senders());
96 }
97 if (c->has_num_watchers()) {
98 channel_builder.add_num_watchers(c->num_watchers());
99 }
100 if (!source_node_offset.IsNull()) {
101 channel_builder.add_source_node(source_node_offset);
102 }
103 if (!destination_nodes_offset.IsNull()) {
104 channel_builder.add_destination_nodes(destination_nodes_offset);
105 }
106 if (c->has_logger()) {
107 channel_builder.add_logger(c->logger());
108 }
109 if (!logger_nodes_offset.IsNull()) {
110 channel_builder.add_logger_nodes(logger_nodes_offset);
111 }
112 if (c->has_read_method()) {
113 channel_builder.add_read_method(c->read_method());
114 }
115 if (c->has_num_readers()) {
116 channel_builder.add_num_readers(c->num_readers());
117 }
118 return channel_builder.Finish();
119}
120
Austin Schuhe309d2a2019-11-29 13:25:21 -0800121namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800122using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700123} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800124
Brian Silverman1f345222020-09-24 21:14:48 -0700125Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
126 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800127 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700128 configuration_(configuration),
129 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700130 timer_handler_(event_loop_->AddTimer(
131 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700132 server_statistics_fetcher_(
133 configuration::MultiNode(event_loop_->configuration())
134 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
135 "/aos")
136 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700137 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700138
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700139 // Find all the nodes which are logging timestamps on our node. This may
140 // over-estimate if should_log is specified.
141 std::vector<const Node *> timestamp_logger_nodes =
142 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700143
144 std::map<const Channel *, const Node *> timestamp_logger_channels;
145
146 // Now that we have all the nodes accumulated, make remote timestamp loggers
147 // for them.
148 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700149 // Note: since we are doing a find using the event loop channel, we need to
150 // make sure this channel pointer is part of the event loop configuration,
151 // not configuration_. This only matters when configuration_ !=
152 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700153 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700154 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700155 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800156 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 event_loop_->node());
158
159 CHECK(channel != nullptr)
160 << ": Remote timestamps are logged on "
161 << event_loop_->node()->name()->string_view()
162 << " but can't find channel /aos/remote_timestamps/"
163 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700164 if (!should_log(channel)) {
165 continue;
166 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700167 timestamp_logger_channels.insert(std::make_pair(channel, node));
168 }
169
Brian Silvermand90905f2020-09-23 14:42:56 -0700170 const size_t our_node_index =
171 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700172
Brian Silverman1f345222020-09-24 21:14:48 -0700173 for (size_t channel_index = 0;
174 channel_index < configuration_->channels()->size(); ++channel_index) {
175 const Channel *const config_channel =
176 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700177 // The MakeRawFetcher method needs a channel which is in the event loop
178 // configuration() object, not the configuration_ object. Go look that up
179 // from the config.
180 const Channel *channel = aos::configuration::GetChannel(
181 event_loop_->configuration(), config_channel->name()->string_view(),
182 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700183 CHECK(channel != nullptr)
184 << ": Failed to look up channel "
185 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700186 if (!should_log(channel)) {
187 continue;
188 }
Austin Schuh0c297012020-09-16 18:41:59 -0700189
Austin Schuhe309d2a2019-11-29 13:25:21 -0800190 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700191 fs.channel_index = channel_index;
192 fs.channel = channel;
193
Austin Schuh6f3babe2020-01-26 20:34:50 -0800194 const bool is_local =
195 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
196
Austin Schuh15649d62019-12-28 16:36:38 -0800197 const bool is_readable =
198 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700199 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
200 channel, event_loop_->node());
201 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800202
Brian Silverman1f345222020-09-24 21:14:48 -0700203 bool log_delivery_times = false;
204 if (event_loop_->node() != nullptr) {
205 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
206 channel, event_loop_->node(), event_loop_->node());
207 }
Austin Schuh15649d62019-12-28 16:36:38 -0800208
Austin Schuh0de30f32020-12-06 12:44:28 -0800209 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700210 // contents to a file directly.
211 const bool log_contents = timestamp_logger_channels.find(channel) !=
212 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700213
214 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800215 fs.fetcher = event_loop->MakeRawFetcher(channel);
216 VLOG(1) << "Logging channel "
217 << configuration::CleanedChannelToString(channel);
218
219 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800220 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700221 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800222 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800223 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 if (log_message) {
225 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700226 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800227 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800228 const Node *source_node = configuration::GetNode(
229 configuration_, channel->source_node()->string_view());
230 fs.data_node_index =
231 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800232 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800233 } else {
234 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800235 }
236 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700237 if (log_contents) {
238 VLOG(1) << "Timestamp logger channel "
239 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700240 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
241 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800242 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700243 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700244 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800245 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800246 }
Brian Silverman1f345222020-09-24 21:14:48 -0700247 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700248
249 // When we are logging remote timestamps, we need to be able to translate from
250 // the channel index that the event loop uses to the channel index in the
251 // config in the log file.
252 event_loop_to_logged_channel_index_.resize(
253 event_loop->configuration()->channels()->size(), -1);
254 for (size_t event_loop_channel_index = 0;
255 event_loop_channel_index <
256 event_loop->configuration()->channels()->size();
257 ++event_loop_channel_index) {
258 const Channel *event_loop_channel =
259 event_loop->configuration()->channels()->Get(event_loop_channel_index);
260
261 const Channel *logged_channel = aos::configuration::GetChannel(
262 configuration_, event_loop_channel->name()->string_view(),
263 event_loop_channel->type()->string_view(), "",
264 configuration::GetNode(configuration_, event_loop_->node()));
265
266 if (logged_channel != nullptr) {
267 event_loop_to_logged_channel_index_[event_loop_channel_index] =
268 configuration::ChannelIndex(configuration_, logged_channel);
269 }
270 }
Brian Silverman1f345222020-09-24 21:14:48 -0700271}
272
273Logger::~Logger() {
274 if (log_namer_) {
275 // If we are replaying a log file, or in simulation, we want to force the
276 // last bit of data to be logged. The easiest way to deal with this is to
277 // poll everything as we go to destroy the class, ie, shut down the logger,
278 // and write it to disk.
279 StopLogging(event_loop_->monotonic_now());
280 }
281}
282
Brian Silvermanae7c0332020-09-30 16:58:23 -0700283void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
284 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700285 CHECK(!log_namer_) << ": Already logging";
286 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700287 log_event_uuid_ = UUID::Random();
288 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700289 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
290
291 // We want to do as much work as possible before the initial Fetch. Time
292 // between that and actually starting to log opens up the possibility of
293 // falling off the end of the queue during that time.
294
295 for (FetcherStruct &f : fetchers_) {
296 if (f.wants_writer) {
297 f.writer = log_namer_->MakeWriter(f.channel);
298 }
299 if (f.wants_timestamp_writer) {
300 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
301 }
302 if (f.wants_contents_writer) {
303 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
304 f.channel, CHECK_NOTNULL(f.timestamp_node));
305 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800306 }
307
Brian Silverman1f345222020-09-24 21:14:48 -0700308 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700309 node_state_.resize(configuration::MultiNode(configuration_)
310 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700311 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800312
Austin Schuh2f8fd752020-09-01 22:38:28 -0700313 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700314 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800315
Austin Schuh2f8fd752020-09-01 22:38:28 -0700316 node_state_[node_index].log_file_header = MakeHeader(node);
317 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800318
Austin Schuh2f8fd752020-09-01 22:38:28 -0700319 // Grab data from each channel right before we declare the log file started
320 // so we can capture the latest message on each channel. This lets us have
321 // non periodic messages with configuration that now get logged.
322 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700323 const auto start = event_loop_->monotonic_now();
324 const bool got_new = f.fetcher->Fetch();
325 const auto end = event_loop_->monotonic_now();
326 RecordFetchResult(start, end, got_new, &f);
327
328 // If there is a message, we want to write it.
329 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700330 }
331
332 // Clear out any old timestamps in case we are re-starting logging.
333 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800334 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
335 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700336 }
337
338 WriteHeader();
339
340 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
341 << " start_time " << last_synchronized_time_;
342
Austin Schuh315b96b2020-12-11 21:21:12 -0800343 // Force logging up until the start of the log file now, so the messages at
344 // the start are always ordered before the rest of the messages.
345 // Note: this ship may have already sailed, but we don't have to make it
346 // worse.
347 // TODO(austin): Test...
348 LogUntil(last_synchronized_time_);
349
Austin Schuh2f8fd752020-09-01 22:38:28 -0700350 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
351 polling_period_);
352}
353
Brian Silverman1f345222020-09-24 21:14:48 -0700354std::unique_ptr<LogNamer> Logger::StopLogging(
355 aos::monotonic_clock::time_point end_time) {
356 CHECK(log_namer_) << ": Not logging right now";
357
358 if (end_time != aos::monotonic_clock::min_time) {
359 LogUntil(end_time);
360 }
361 timer_handler_->Disable();
362
363 for (FetcherStruct &f : fetchers_) {
364 f.writer = nullptr;
365 f.timestamp_writer = nullptr;
366 f.contents_writer = nullptr;
367 }
368 node_state_.clear();
369
Brian Silvermanae7c0332020-09-30 16:58:23 -0700370 log_event_uuid_ = UUID::Zero();
371 log_start_uuid_ = std::string();
372
Brian Silverman1f345222020-09-24 21:14:48 -0700373 return std::move(log_namer_);
374}
375
Austin Schuhfa895892020-01-07 20:07:41 -0800376void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700377 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700378 server_statistics_fetcher_.Fetch();
379 }
380
381 aos::monotonic_clock::time_point monotonic_start_time =
382 event_loop_->monotonic_now();
383 aos::realtime_clock::time_point realtime_start_time =
384 event_loop_->realtime_now();
385
386 // We need to pick a point in time to declare the log file "started". This
387 // starts here. It needs to be after everything is fetched so that the
388 // fetchers are all pointed at the most recent message before the start
389 // time.
390 last_synchronized_time_ = monotonic_start_time;
391
Austin Schuh6f3babe2020-01-26 20:34:50 -0800392 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700393 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700394 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
395 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800396 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800397 }
398}
Austin Schuh8bd96322020-02-13 21:18:22 -0800399
Austin Schuh315b96b2020-12-11 21:21:12 -0800400void Logger::MaybeWriteHeader(int node_index) {
401 if (configuration::MultiNode(configuration_)) {
402 return MaybeWriteHeader(node_index,
403 configuration_->nodes()->Get(node_index));
404 } else {
405 return MaybeWriteHeader(node_index, nullptr);
406 }
407}
408
409void Logger::MaybeWriteHeader(int node_index, const Node *node) {
410 // This function is responsible for writing the header when the header both
411 // has valid data, and when it needs to be written.
412 if (node_state_[node_index].header_written &&
413 node_state_[node_index].header_valid) {
414 // The header has been written and is valid, nothing to do.
415 return;
416 }
417 if (!node_state_[node_index].has_source_node_boot_uuid) {
418 // Can't write a header if we don't have the boot UUID.
419 return;
420 }
421
422 // WriteHeader writes the first header in a log file. We want to do this only
423 // once.
424 //
425 // Rotate rewrites the same header with a new part ID, but keeps the same part
426 // UUID. We don't want that when things reboot, because that implies that
427 // parts go together across a reboot.
428 //
429 // Reboot resets the parts UUID. So, once we've written a header the first
430 // time, we want to use Reboot to rotate the log and reset the parts UUID.
431 //
432 // header_valid is cleared whenever the remote reboots.
433 if (node_state_[node_index].header_written) {
434 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
435 } else {
436 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
437
438 node_state_[node_index].header_written = true;
439 }
440 node_state_[node_index].header_valid = true;
441}
442
Austin Schuh2f8fd752020-09-01 22:38:28 -0700443void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700444 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700445 server_statistics_fetcher_.Fetch();
446 } else {
447 return;
448 }
449
450 if (server_statistics_fetcher_.get() == nullptr) {
451 return;
452 }
453
454 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700455 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700456 if (MaybeUpdateTimestamp(
457 node, node_index,
458 server_statistics_fetcher_.context().monotonic_event_time,
459 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800460 CHECK(node_state_[node_index].header_written);
461 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700462 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800463 } else {
464 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700465 }
466 }
467}
468
Austin Schuh315b96b2020-12-11 21:21:12 -0800469void Logger::SetStartTime(
470 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
471 aos::realtime_clock::time_point realtime_start_time,
472 aos::monotonic_clock::time_point logger_monotonic_start_time,
473 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700474 node_state_[node_index].monotonic_start_time = monotonic_start_time;
475 node_state_[node_index].realtime_start_time = realtime_start_time;
476 node_state_[node_index]
477 .log_file_header.mutable_message()
478 ->mutate_monotonic_start_time(
479 std::chrono::duration_cast<std::chrono::nanoseconds>(
480 monotonic_start_time.time_since_epoch())
481 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800482
483 // Add logger start times if they are available in the log file header.
484 if (node_state_[node_index]
485 .log_file_header.mutable_message()
486 ->has_logger_monotonic_start_time()) {
487 node_state_[node_index]
488 .log_file_header.mutable_message()
489 ->mutate_logger_monotonic_start_time(
490 std::chrono::duration_cast<std::chrono::nanoseconds>(
491 logger_monotonic_start_time.time_since_epoch())
492 .count());
493 }
494
495 if (node_state_[node_index]
496 .log_file_header.mutable_message()
497 ->has_logger_realtime_start_time()) {
498 node_state_[node_index]
499 .log_file_header.mutable_message()
500 ->mutate_logger_realtime_start_time(
501 std::chrono::duration_cast<std::chrono::nanoseconds>(
502 logger_realtime_start_time.time_since_epoch())
503 .count());
504 }
505
Austin Schuh2f8fd752020-09-01 22:38:28 -0700506 if (node_state_[node_index]
507 .log_file_header.mutable_message()
508 ->has_realtime_start_time()) {
509 node_state_[node_index]
510 .log_file_header.mutable_message()
511 ->mutate_realtime_start_time(
512 std::chrono::duration_cast<std::chrono::nanoseconds>(
513 realtime_start_time.time_since_epoch())
514 .count());
515 }
516}
517
518bool Logger::MaybeUpdateTimestamp(
519 const Node *node, int node_index,
520 aos::monotonic_clock::time_point monotonic_start_time,
521 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700522 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700523 if (node_state_[node_index].monotonic_start_time !=
524 monotonic_clock::min_time) {
525 return false;
526 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800527 if (event_loop_->node() == node ||
528 !configuration::MultiNode(configuration_)) {
529 // There are no offsets to compute for ourself, so always succeed.
530 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
531 monotonic_start_time, realtime_start_time);
532 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700533 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800534 } else if (server_statistics_fetcher_.get() != nullptr) {
535 // We must be a remote node now. Look for the connection and see if it is
536 // connected.
537
538 for (const message_bridge::ServerConnection *connection :
539 *server_statistics_fetcher_->connections()) {
540 if (connection->node()->name()->string_view() !=
541 node->name()->string_view()) {
542 continue;
543 }
544
545 if (connection->state() != message_bridge::State::CONNECTED) {
546 VLOG(1) << node->name()->string_view()
547 << " is not connected, can't start it yet.";
548 break;
549 }
550
551 // Update the boot UUID as soon as we know we are connected.
552 if (!connection->has_boot_uuid()) {
553 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
554 break;
555 }
556
557 if (!node_state_[node_index].has_source_node_boot_uuid ||
558 node_state_[node_index].source_node_boot_uuid !=
559 connection->boot_uuid()->string_view()) {
560 node_state_[node_index].SetBootUUID(
561 connection->boot_uuid()->string_view());
562 }
563
564 if (!connection->has_monotonic_offset()) {
565 VLOG(1) << "Missing monotonic offset for setting start time for node "
566 << aos::FlatbufferToJson(node);
567 break;
568 }
569
570 // Found it and it is connected. Compensate and go.
571 SetStartTime(node_index,
572 monotonic_start_time +
573 std::chrono::nanoseconds(connection->monotonic_offset()),
574 realtime_start_time, monotonic_start_time,
575 realtime_start_time);
576 return true;
577 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700578 }
579 return false;
580}
581
582aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
583 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800584 // Now write the header with this timestamp in it.
585 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800586 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800587
Austin Schuh2f8fd752020-09-01 22:38:28 -0700588 // TODO(austin): Compress this much more efficiently. There are a bunch of
589 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700590 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700591 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800592
Brian Silvermanae7c0332020-09-30 16:58:23 -0700593 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700594 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800595
Brian Silvermanae7c0332020-09-30 16:58:23 -0700596 CHECK(log_event_uuid_ != UUID::Zero());
597 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
598 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700599
Brian Silvermanae7c0332020-09-30 16:58:23 -0700600 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
601 fbb.CreateString(logger_instance_uuid_.string_view());
602
603 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
604 if (!log_start_uuid_.empty()) {
605 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
606 }
607
Austin Schuh315b96b2020-12-11 21:21:12 -0800608 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
609 fbb.CreateString(event_loop_->boot_uuid().string_view());
610
611 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
612 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700613
614 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700615 fbb.CreateString("00000000-0000-4000-8000-000000000000");
616
Austin Schuhfa895892020-01-07 20:07:41 -0800617 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700618 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700619
Austin Schuh0c297012020-09-16 18:41:59 -0700620 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800621 // TODO(austin): Reuse the node we just copied in above.
622 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
623 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800624 }
625
626 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
627
Austin Schuh64fab802020-09-09 22:47:47 -0700628 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800629
630 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800631 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800632 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700633 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800634 }
635
636 log_file_header_builder.add_configuration(configuration_offset);
637 // The worst case theoretical out of order is the polling period times 2.
638 // One message could get logged right after the boundary, but be for right
639 // before the next boundary. And the reverse could happen for another
640 // message. Report back 3x to be extra safe, and because the cost isn't
641 // huge on the read side.
642 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700643 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800644
645 log_file_header_builder.add_monotonic_start_time(
646 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700647 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800648 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700649 if (node == event_loop_->node()) {
650 log_file_header_builder.add_realtime_start_time(
651 std::chrono::duration_cast<std::chrono::nanoseconds>(
652 realtime_clock::min_time.time_since_epoch())
653 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800654 } else {
655 log_file_header_builder.add_logger_monotonic_start_time(
656 std::chrono::duration_cast<std::chrono::nanoseconds>(
657 monotonic_clock::min_time.time_since_epoch())
658 .count());
659 log_file_header_builder.add_logger_realtime_start_time(
660 std::chrono::duration_cast<std::chrono::nanoseconds>(
661 realtime_clock::min_time.time_since_epoch())
662 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800663 }
664
Brian Silvermanae7c0332020-09-30 16:58:23 -0700665 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
666 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
667 if (!log_start_uuid_offset.IsNull()) {
668 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
669 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800670 log_file_header_builder.add_logger_node_boot_uuid(
671 logger_node_boot_uuid_offset);
672 log_file_header_builder.add_source_node_boot_uuid(
673 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700674
675 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
676 log_file_header_builder.add_parts_index(0);
677
Austin Schuh2f8fd752020-09-01 22:38:28 -0700678 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800679 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
680 fbb.Release());
681
682 CHECK(result.Verify()) << ": Built a corrupted header.";
683
684 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700685}
686
Brian Silvermancb805822020-10-06 17:43:35 -0700687void Logger::ResetStatisics() {
688 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
689 max_message_fetch_time_channel_ = -1;
690 max_message_fetch_time_size_ = -1;
691 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
692 total_message_fetch_count_ = 0;
693 total_message_fetch_bytes_ = 0;
694 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
695 total_nop_fetch_count_ = 0;
696 max_copy_time_ = std::chrono::nanoseconds::zero();
697 max_copy_time_channel_ = -1;
698 max_copy_time_size_ = -1;
699 total_copy_time_ = std::chrono::nanoseconds::zero();
700 total_copy_count_ = 0;
701 total_copy_bytes_ = 0;
702}
703
Austin Schuh2f8fd752020-09-01 22:38:28 -0700704void Logger::Rotate() {
705 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700706 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700707 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700708 }
709}
710
711void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800712 // Grab the latest ServerStatistics message. This will always have the
713 // oppertunity to be >= to the current time, so it will always represent any
714 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700715 WriteMissingTimestamps();
716
717 // Write each channel to disk, one at a time.
718 for (FetcherStruct &f : fetchers_) {
719 while (true) {
720 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700721 const auto start = event_loop_->monotonic_now();
722 const bool got_new = f.fetcher->FetchNext();
723 const auto end = event_loop_->monotonic_now();
724 RecordFetchResult(start, end, got_new, &f);
725 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700726 VLOG(2) << "No new data on "
727 << configuration::CleanedChannelToString(
728 f.fetcher->channel());
729 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700730 }
Brian Silvermancb805822020-10-06 17:43:35 -0700731 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700732 }
733
Austin Schuh2f8fd752020-09-01 22:38:28 -0700734 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700735 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 break;
737 }
Brian Silvermancb805822020-10-06 17:43:35 -0700738 if (f.writer != nullptr) {
739 // Write!
740 const auto start = event_loop_->monotonic_now();
741 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
742 max_header_size_);
743 fbb.ForceDefaults(true);
744
745 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
746 f.channel_index, f.log_type));
747 const auto end = event_loop_->monotonic_now();
748 RecordCreateMessageTime(start, end, &f);
749
750 VLOG(2) << "Writing data as node "
751 << FlatbufferToJson(event_loop_->node()) << " for channel "
752 << configuration::CleanedChannelToString(f.fetcher->channel())
753 << " to " << f.writer->filename() << " data "
754 << FlatbufferToJson(
755 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
756 fbb.GetBufferPointer()));
757
758 max_header_size_ = std::max(max_header_size_,
759 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800760 CHECK(node_state_[f.data_node_index].header_valid)
761 << ": Can't write data before the header on channel "
762 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700763 f.writer->QueueSizedFlatbuffer(&fbb);
764 }
765
766 if (f.timestamp_writer != nullptr) {
767 // And now handle timestamps.
768 const auto start = event_loop_->monotonic_now();
769 flatbuffers::FlatBufferBuilder fbb;
770 fbb.ForceDefaults(true);
771
772 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
773 f.channel_index,
774 LogType::kLogDeliveryTimeOnly));
775 const auto end = event_loop_->monotonic_now();
776 RecordCreateMessageTime(start, end, &f);
777
778 VLOG(2) << "Writing timestamps as node "
779 << FlatbufferToJson(event_loop_->node()) << " for channel "
780 << configuration::CleanedChannelToString(f.fetcher->channel())
781 << " to " << f.timestamp_writer->filename() << " timestamp "
782 << FlatbufferToJson(
783 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
784 fbb.GetBufferPointer()));
785
Austin Schuh315b96b2020-12-11 21:21:12 -0800786 CHECK(node_state_[f.timestamp_node_index].header_valid)
787 << ": Can't write data before the header on channel "
788 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700789 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
790 }
791
792 if (f.contents_writer != nullptr) {
793 const auto start = event_loop_->monotonic_now();
794 // And now handle the special message contents channel. Copy the
795 // message into a FlatBufferBuilder and save it to disk.
796 // TODO(austin): We can be more efficient here when we start to
797 // care...
798 flatbuffers::FlatBufferBuilder fbb;
799 fbb.ForceDefaults(true);
800
Austin Schuh0de30f32020-12-06 12:44:28 -0800801 const RemoteMessage *msg =
802 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700803
Austin Schuh315b96b2020-12-11 21:21:12 -0800804 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
805 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
806 node_state_[f.contents_node_index].source_node_boot_uuid !=
807 msg->boot_uuid()->string_view()) {
808 node_state_[f.contents_node_index].SetBootUUID(
809 msg->boot_uuid()->string_view());
810
811 MaybeWriteHeader(f.contents_node_index);
812 }
813
Brian Silvermancb805822020-10-06 17:43:35 -0700814 logger::MessageHeader::Builder message_header_builder(fbb);
815
816 // TODO(austin): This needs to check the channel_index and confirm
817 // that it should be logged before squirreling away the timestamp to
818 // disk. We don't want to log irrelevant timestamps.
819
820 // Note: this must match the same order as MessageBridgeServer and
821 // PackMessage. We want identical headers to have identical
822 // on-the-wire formats to make comparing them easier.
823
824 // Translate from the channel index that the event loop uses to the
825 // channel index in the log file.
826 message_header_builder.add_channel_index(
827 event_loop_to_logged_channel_index_[msg->channel_index()]);
828
829 message_header_builder.add_queue_index(msg->queue_index());
830 message_header_builder.add_monotonic_sent_time(
831 msg->monotonic_sent_time());
832 message_header_builder.add_realtime_sent_time(
833 msg->realtime_sent_time());
834
835 message_header_builder.add_monotonic_remote_time(
836 msg->monotonic_remote_time());
837 message_header_builder.add_realtime_remote_time(
838 msg->realtime_remote_time());
839 message_header_builder.add_remote_queue_index(
840 msg->remote_queue_index());
841
842 fbb.FinishSizePrefixed(message_header_builder.Finish());
843 const auto end = event_loop_->monotonic_now();
844 RecordCreateMessageTime(start, end, &f);
845
Austin Schuh315b96b2020-12-11 21:21:12 -0800846 CHECK(node_state_[f.contents_node_index].header_valid)
847 << ": Can't write data before the header on channel "
848 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700849 f.contents_writer->QueueSizedFlatbuffer(&fbb);
850 }
851
852 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700853 }
854 }
855 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800856}
857
Brian Silverman1f345222020-09-24 21:14:48 -0700858void Logger::DoLogData(const monotonic_clock::time_point end_time) {
859 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800860 // max_out_of_order_duration. To do this, we need sync points. Every write
861 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800862
863 do {
864 // Move the sync point up by at most polling_period. This forces one sync
865 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700866 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
867
868 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800869
Austin Schuhe309d2a2019-11-29 13:25:21 -0800870 // If we missed cycles, we could be pretty far behind. Spin until we are
871 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700872 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800873}
874
Brian Silvermancb805822020-10-06 17:43:35 -0700875void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
876 aos::monotonic_clock::time_point end,
877 bool got_new, FetcherStruct *fetcher) {
878 const auto duration = end - start;
879 if (!got_new) {
880 ++total_nop_fetch_count_;
881 total_nop_fetch_time_ += duration;
882 return;
883 }
884 ++total_message_fetch_count_;
885 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
886 total_message_fetch_time_ += duration;
887 if (duration > max_message_fetch_time_) {
888 max_message_fetch_time_ = duration;
889 max_message_fetch_time_channel_ = fetcher->channel_index;
890 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
891 }
892}
893
894void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
895 aos::monotonic_clock::time_point end,
896 FetcherStruct *fetcher) {
897 const auto duration = end - start;
898 total_copy_time_ += duration;
899 ++total_copy_count_;
900 total_copy_bytes_ += fetcher->fetcher->context().size;
901 if (duration > max_copy_time_) {
902 max_copy_time_ = duration;
903 max_copy_time_channel_ = fetcher->channel_index;
904 max_copy_time_size_ = fetcher->fetcher->context().size;
905 }
906}
907
Austin Schuh11d43732020-09-21 17:28:30 -0700908std::vector<std::vector<std::string>> ToLogReaderVector(
909 const std::vector<LogFile> &log_files) {
910 std::vector<std::vector<std::string>> result;
911 for (const LogFile &log_file : log_files) {
912 for (const LogParts &log_parts : log_file.parts) {
913 std::vector<std::string> parts;
914 for (const std::string &part : log_parts.parts) {
915 parts.emplace_back(part);
916 }
917 result.emplace_back(std::move(parts));
918 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700919 }
920 return result;
921}
922
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800923LogReader::LogReader(std::string_view filename,
924 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800925 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800926
Austin Schuh287d43d2020-12-04 20:19:33 -0800927LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800928 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800929 : log_files_(std::move(log_files)),
930 log_file_header_(MaybeReadHeaderOrDie(log_files_)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800931 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800932 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800933
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700934 // Remap all existing remote timestamp channels. They will be recreated, and
935 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700936 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700937 std::vector<const Node *> timestamp_logger_nodes =
938 configuration::TimestampNodes(logged_configuration(), node);
939 for (const Node *remote_node : timestamp_logger_nodes) {
940 const std::string channel = absl::StrCat(
941 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800942 // See if the log file is an old log with MessageHeader channels in it, or
943 // a newer log with RemoteMessage. If we find an older log, rename the
944 // type too along with the name.
945 if (HasChannel<MessageHeader>(channel, node)) {
946 CHECK(!HasChannel<RemoteMessage>(channel, node))
947 << ": Can't have both a MessageHeader and RemoteMessage remote "
948 "timestamp channel.";
949 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
950 "aos.message_bridge.RemoteMessage");
951 } else {
952 CHECK(HasChannel<RemoteMessage>(channel, node))
953 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
954 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
955 << node->name()->string_view();
956 RemapLoggedChannel<RemoteMessage>(channel, node);
957 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700958 }
959 }
960
Austin Schuh6aa77be2020-02-22 21:06:40 -0800961 if (replay_configuration) {
962 CHECK_EQ(configuration::MultiNode(configuration()),
963 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700964 << ": Log file and replay config need to both be multi or single "
965 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800966 }
967
Austin Schuh6f3babe2020-01-26 20:34:50 -0800968 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800969 states_.emplace_back(std::make_unique<State>(
970 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800971 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800972 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700973 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800974 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700975 << ": Log file and replay config need to have matching nodes "
976 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700977 for (const Node *node : *logged_configuration()->nodes()) {
978 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700979 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
980 << " in logged config that is not present in the replay "
981 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700982 }
983 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800984 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800985 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800986 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800987}
988
Austin Schuh6aa77be2020-02-22 21:06:40 -0800989LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700990 if (event_loop_factory_unique_ptr_) {
991 Deregister();
992 } else if (event_loop_factory_ != nullptr) {
993 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
994 "is destroyed";
995 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800996 if (offset_fp_ != nullptr) {
997 fclose(offset_fp_);
998 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700999 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1000 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001001 if (remapped_configuration_buffer_) {
1002 remapped_configuration_buffer_->Wipe();
1003 }
1004 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -08001005}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001006
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001007const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001008 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001009}
1010
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001011const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001012 return remapped_configuration_;
1013}
1014
Austin Schuh6f3babe2020-01-26 20:34:50 -08001015std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 // Because the Node pointer will only be valid if it actually points to
1017 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001018 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001019 //
1020 // Also, note, that when ever a map is changed, the nodes in here are
1021 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001022 CHECK(remapped_configuration_ != nullptr)
1023 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001024 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001025}
Austin Schuh15649d62019-12-28 16:36:38 -08001026
Austin Schuh11d43732020-09-21 17:28:30 -07001027monotonic_clock::time_point LogReader::monotonic_start_time(
1028 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001029 State *state =
1030 states_[configuration::GetNodeIndex(configuration(), node)].get();
1031 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1032
Austin Schuh858c9f32020-08-31 16:56:12 -07001033 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001034}
1035
Austin Schuh11d43732020-09-21 17:28:30 -07001036realtime_clock::time_point LogReader::realtime_start_time(
1037 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001038 State *state =
1039 states_[configuration::GetNodeIndex(configuration(), node)].get();
1040 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1041
Austin Schuh858c9f32020-08-31 16:56:12 -07001042 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001043}
1044
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001045void LogReader::Register() {
1046 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001047 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001048 Register(event_loop_factory_unique_ptr_.get());
1049}
1050
Austin Schuh92547522019-12-28 14:33:43 -08001051void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001052 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001053 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -08001054
Brian Silvermand90905f2020-09-23 14:42:56 -07001055 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001056 const size_t node_index =
1057 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001058 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1059 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001060
1061 // Confirm that all the parts are from the same boot if there are enough
1062 // parts to not be from the same boot.
1063 if (filtered_parts.size() > 1u) {
1064 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1065 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1066 filtered_parts[0].source_boot_uuid)
1067 << ": Found parts from different boots "
1068 << LogFileVectorToString(log_files_);
1069 }
1070 }
1071
Austin Schuh287d43d2020-12-04 20:19:33 -08001072 states_[node_index] = std::make_unique<State>(
1073 filtered_parts.size() == 0u
1074 ? nullptr
1075 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001076 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001077 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001078 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001079
1080 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001081 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001082
Austin Schuh287d43d2020-12-04 20:19:33 -08001083 for (const Node *node : configuration::GetNodes(configuration())) {
1084 const size_t node_index =
1085 configuration::GetNodeIndex(configuration(), node);
1086 State *state = states_[node_index].get();
1087 for (const Node *other_node : configuration::GetNodes(configuration())) {
1088 const size_t other_node_index =
1089 configuration::GetNodeIndex(configuration(), other_node);
1090 State *other_state = states_[other_node_index].get();
1091 if (other_state != state) {
1092 state->AddPeer(other_state);
1093 }
1094 }
1095 }
1096
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001097 // Register after making all the State objects so we can build references
1098 // between them.
1099 for (const Node *node : configuration::GetNodes(configuration())) {
1100 const size_t node_index =
1101 configuration::GetNodeIndex(configuration(), node);
1102 State *state = states_[node_index].get();
1103
1104 Register(state->event_loop());
1105 }
1106
James Kuszmaul46d82582020-05-09 19:50:09 -07001107 if (live_nodes_ == 0) {
1108 LOG(FATAL)
1109 << "Don't have logs from any of the nodes in the replay config--are "
1110 "you sure that the replay config matches the original config?";
1111 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001112
Austin Schuh2f8fd752020-09-01 22:38:28 -07001113 // We need to now seed our per-node time offsets and get everything set up
1114 // to run.
1115 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -08001116
Austin Schuh8bd96322020-02-13 21:18:22 -08001117 // It is easiest to solve for per node offsets with a matrix rather than
1118 // trying to solve the equations by hand. So let's get after it.
1119 //
1120 // Now, build up the map matrix.
1121 //
Austin Schuh2f8fd752020-09-01 22:38:28 -07001122 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
1123 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1124 filters_.size() + 1, num_nodes);
1125 slope_matrix_ =
1126 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1127 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -08001128
Austin Schuh2f8fd752020-09-01 22:38:28 -07001129 offset_matrix_ =
1130 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1131 valid_matrix_ =
1132 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1133 last_valid_matrix_ =
1134 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -08001135
Austin Schuh2f8fd752020-09-01 22:38:28 -07001136 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
1137 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -08001138
Austin Schuh2f8fd752020-09-01 22:38:28 -07001139 // All times should average out to the distributed clock.
1140 for (int i = 0; i < map_matrix_.cols(); ++i) {
1141 // 1/num_nodes.
1142 map_matrix_(0, i) = mpq_class(1, num_nodes);
1143 }
1144 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -08001145
1146 {
1147 // Now, add the a - b -> sample elements.
1148 size_t i = 1;
1149 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001150 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1151 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001152 const Node *const node_a = std::get<0>(filter.first);
1153 const Node *const node_b = std::get<1>(filter.first);
1154
1155 const size_t node_a_index =
1156 configuration::GetNodeIndex(configuration(), node_a);
1157 const size_t node_b_index =
1158 configuration::GetNodeIndex(configuration(), node_b);
1159
Austin Schuh2f8fd752020-09-01 22:38:28 -07001160 // -a
1161 map_matrix_(i, node_a_index) = mpq_class(-1);
1162 // +b
1163 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -08001164
1165 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -07001166 std::get<0>(filter.second)
1167 .set_slope_pointer(&slope_matrix_(i, node_a_index));
1168 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
1169
1170 valid_matrix_(i) = false;
1171 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -08001172
1173 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001174 }
1175 }
1176
Austin Schuh858c9f32020-08-31 16:56:12 -07001177 for (std::unique_ptr<State> &state : states_) {
1178 state->SeedSortedMessages();
1179 }
1180
Austin Schuh2f8fd752020-09-01 22:38:28 -07001181 // Rank of the map matrix tells you if all the nodes are in communication
1182 // with each other, which tells you if the offsets are observable.
1183 const size_t connected_nodes =
1184 Eigen::FullPivLU<
1185 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
1186 .rank();
1187
1188 // We don't need to support isolated nodes until someone has a real use
1189 // case.
1190 CHECK_EQ(connected_nodes, num_nodes)
1191 << ": There is a node which isn't communicating with the rest.";
1192
1193 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001194 UpdateOffsets();
1195
Austin Schuh2f8fd752020-09-01 22:38:28 -07001196 // We want to start the log file at the last start time of the log files
1197 // from all the nodes. Compute how long each node's simulation needs to run
1198 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001199 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001200
Austin Schuh2f8fd752020-09-01 22:38:28 -07001201 // TODO(austin): We want an "OnStart" callback for each node rather than
1202 // running until the last node.
1203
Austin Schuh8bd96322020-02-13 21:18:22 -08001204 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1206 << MaybeNodeName(state->event_loop()->node()) << "now "
1207 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001208 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1209 continue;
1210 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001211 // And start computing the start time on the distributed clock now that
1212 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001213 start_time = std::max(
1214 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001215 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001216
1217 CHECK_GE(start_time, distributed_clock::epoch())
1218 << ": Hmm, we have a node starting before the start of time. Offset "
1219 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001220
Austin Schuh6f3babe2020-01-26 20:34:50 -08001221 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1222 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001223 // nodes, and also replayed on the other nodes. This may not satisfy all
1224 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1226 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1227 const Channel *channel = logged_configuration()->channels()->Get(i);
1228 const Node *node = configuration::GetNode(
1229 configuration(), channel->source_node()->string_view());
1230
Austin Schuh8bd96322020-02-13 21:18:22 -08001231 State *state =
1232 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001233
1234 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001235 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001236
1237 event_loop_factory_->DisableForwarding(remapped_channel);
1238 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001239
1240 // If we are replaying a log, we don't want a bunch of redundant messages
1241 // from both the real message bridge and simulated message bridge.
1242 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001243 }
1244
Austin Schuhcde938c2020-02-02 17:30:07 -08001245 // While we are starting the system up, we might be relying on matching data
1246 // to timestamps on log files where the timestamp log file starts before the
1247 // data. In this case, it is reasonable to expect missing data.
1248 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001249 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001250 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001251 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001252 // Now that we are running for real, missing data means that the log file is
1253 // corrupted or went wrong.
1254 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001255
Austin Schuh8bd96322020-02-13 21:18:22 -08001256 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001257 // Make the RT clock be correct before handing it to the user.
1258 if (state->realtime_start_time() != realtime_clock::min_time) {
1259 state->SetRealtimeOffset(state->monotonic_start_time(),
1260 state->realtime_start_time());
1261 }
1262 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1263 << MaybeNodeName(state->event_loop()->node()) << "now "
1264 << state->monotonic_now();
1265 }
1266
1267 if (FLAGS_timestamps_to_csv) {
1268 for (std::pair<const std::tuple<const Node *, const Node *>,
1269 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1270 &filter : filters_) {
1271 const Node *const node_a = std::get<0>(filter.first);
1272 const Node *const node_b = std::get<1>(filter.first);
1273
1274 std::get<0>(filter.second)
1275 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1276 ->monotonic_now());
1277 std::get<0>(filter.second)
1278 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1279 ->monotonic_now());
1280 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001281 }
1282}
1283
Austin Schuh2f8fd752020-09-01 22:38:28 -07001284void LogReader::UpdateOffsets() {
1285 VLOG(2) << "Samples are " << offset_matrix_;
1286 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1287 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1288 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1289 "]");
1290 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1291 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1292
1293 size_t node_index = 0;
1294 for (std::unique_ptr<State> &state : states_) {
1295 state->SetDistributedOffset(offset(node_index), slope(node_index));
1296 VLOG(1) << "Offset for node " << node_index << " "
1297 << MaybeNodeName(state->event_loop()->node()) << "is "
1298 << aos::distributed_clock::time_point(offset(node_index))
1299 << " slope " << std::setprecision(9) << std::fixed
1300 << slope(node_index);
1301 ++node_index;
1302 }
1303
1304 if (VLOG_IS_ON(1)) {
1305 LogFit("Offset is");
1306 }
1307}
1308
1309void LogReader::LogFit(std::string_view prefix) {
1310 for (std::unique_ptr<State> &state : states_) {
1311 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1312 << state->monotonic_now() << " distributed "
1313 << event_loop_factory_->distributed_now();
1314 }
1315
1316 for (std::pair<const std::tuple<const Node *, const Node *>,
1317 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1318 filters_) {
1319 message_bridge::NoncausalOffsetEstimator *estimator =
1320 &std::get<0>(filter.second);
1321
1322 if (estimator->a_timestamps().size() == 0 &&
1323 estimator->b_timestamps().size() == 0) {
1324 continue;
1325 }
1326
1327 if (VLOG_IS_ON(1)) {
1328 estimator->LogFit(prefix);
1329 }
1330
1331 const Node *const node_a = std::get<0>(filter.first);
1332 const Node *const node_b = std::get<1>(filter.first);
1333
1334 const size_t node_a_index =
1335 configuration::GetNodeIndex(configuration(), node_a);
1336 const size_t node_b_index =
1337 configuration::GetNodeIndex(configuration(), node_b);
1338
1339 const double recovered_slope =
1340 slope(node_b_index) / slope(node_a_index) - 1.0;
1341 const int64_t recovered_offset =
1342 offset(node_b_index).count() - offset(node_a_index).count() *
1343 slope(node_b_index) /
1344 slope(node_a_index);
1345
1346 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1347 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1348 << " offset " << std::setprecision(20) << recovered_offset
1349 << " (error "
1350 << recovered_offset - estimator->fit().offset().count() << ")";
1351
1352 const aos::distributed_clock::time_point a0 =
1353 states_[node_a_index]->ToDistributedClock(
1354 std::get<0>(estimator->a_timestamps()[0]));
1355 const aos::distributed_clock::time_point a1 =
1356 states_[node_a_index]->ToDistributedClock(
1357 std::get<0>(estimator->a_timestamps()[1]));
1358
1359 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1360 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1361 << " distributed -> " << node_b->name()->string_view() << " "
1362 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1363 << aos::monotonic_clock::time_point(
1364 std::chrono::nanoseconds(static_cast<int64_t>(
1365 std::get<0>(estimator->a_timestamps()[0])
1366 .time_since_epoch()
1367 .count() *
1368 (1.0 + estimator->fit().slope()))) +
1369 estimator->fit().offset())
1370 << ((a0 <= event_loop_factory_->distributed_now())
1371 ? ""
1372 : " After now, investigate");
1373 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1374 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1375 << " distributed -> " << node_b->name()->string_view() << " "
1376 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1377 << aos::monotonic_clock::time_point(
1378 std::chrono::nanoseconds(static_cast<int64_t>(
1379 std::get<0>(estimator->a_timestamps()[1])
1380 .time_since_epoch()
1381 .count() *
1382 (1.0 + estimator->fit().slope()))) +
1383 estimator->fit().offset())
1384 << ((event_loop_factory_->distributed_now() <= a1)
1385 ? ""
1386 : " Before now, investigate");
1387
1388 const aos::distributed_clock::time_point b0 =
1389 states_[node_b_index]->ToDistributedClock(
1390 std::get<0>(estimator->b_timestamps()[0]));
1391 const aos::distributed_clock::time_point b1 =
1392 states_[node_b_index]->ToDistributedClock(
1393 std::get<0>(estimator->b_timestamps()[1]));
1394
1395 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1396 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1397 << " distributed -> " << node_a->name()->string_view() << " "
1398 << states_[node_a_index]->FromDistributedClock(b0)
1399 << ((b0 <= event_loop_factory_->distributed_now())
1400 ? ""
1401 : " After now, investigate");
1402 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1403 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1404 << " distributed -> " << node_a->name()->string_view() << " "
1405 << states_[node_a_index]->FromDistributedClock(b1)
1406 << ((event_loop_factory_->distributed_now() <= b1)
1407 ? ""
1408 : " Before now, investigate");
1409 }
1410}
1411
1412message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001413 const Node *node_a, const Node *node_b) {
1414 CHECK_NE(node_a, node_b);
1415 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1416 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1417
1418 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001419 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001420 }
1421
1422 auto tuple = std::make_tuple(node_a, node_b);
1423
1424 auto it = filters_.find(tuple);
1425
1426 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001427 auto &x =
1428 filters_
1429 .insert(std::make_pair(
1430 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1431 node_a, node_b))))
1432 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001433 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001434 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1435 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1436 node_b->name()->string_view()));
1437 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1438 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1439 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001440 }
1441
Austin Schuh2f8fd752020-09-01 22:38:28 -07001442 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001443 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001444 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001445 }
1446}
1447
Austin Schuhe309d2a2019-11-29 13:25:21 -08001448void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001449 State *state =
1450 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1451 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001452
Austin Schuh858c9f32020-08-31 16:56:12 -07001453 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001454
Tyler Chatow67ddb032020-01-12 14:30:04 -08001455 // We don't run timing reports when trying to print out logged data, because
1456 // otherwise we would end up printing out the timing reports themselves...
1457 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001458 event_loop->SkipTimingReport();
1459 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001460
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001461 for (size_t logged_channel_index = 0;
1462 logged_channel_index < logged_configuration()->channels()->size();
1463 ++logged_channel_index) {
1464 const Channel *channel = RemapChannel(
1465 event_loop,
1466 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001467
Austin Schuh2f8fd752020-09-01 22:38:28 -07001468 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001469 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001470
1471 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001472
1473 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1474 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001475 // We've got a message which is being forwarded to this node.
1476 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001477 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001478 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001479
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001480 // Delivery timestamps are supposed to be logged back on the source node.
1481 // Configure remote timestamps to be sent.
1482 const bool delivery_time_is_logged =
1483 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1484 channel, event_loop->node(), source_node);
1485
1486 source_state =
1487 states_[configuration::GetNodeIndex(configuration(), source_node)]
1488 .get();
1489
1490 if (delivery_time_is_logged) {
1491 remote_timestamp_sender =
1492 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001493 }
1494 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001495
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001496 state->SetChannel(
1497 logged_channel_index,
1498 configuration::ChannelIndex(event_loop->configuration(), channel),
1499 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1500 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001501 }
1502
Austin Schuh6aa77be2020-02-22 21:06:40 -08001503 // If we didn't find any log files with data in them, we won't ever get a
1504 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001505 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001506 return;
1507 }
1508
Austin Schuh858c9f32020-08-31 16:56:12 -07001509 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001510 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1511 << "at " << state->event_loop()->context().monotonic_event_time
1512 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001513 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001514 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001515 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001516 if (live_nodes_ == 0) {
1517 event_loop_factory_->Exit();
1518 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001519 return;
1520 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001521 if (VLOG_IS_ON(1)) {
1522 LogFit("Offset was");
1523 }
1524
1525 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001526 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001527
Austin Schuhe309d2a2019-11-29 13:25:21 -08001528 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001529 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001530 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001531 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001532 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1533 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001534 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001535 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001536 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001537 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001538 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001539 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001540 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001541 << "): " << FlatbufferToJson(state->event_loop()->node())
1542 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001543 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001544 << state->DebugString();
1545 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001546
Austin Schuh287d43d2020-12-04 20:19:33 -08001547 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001548 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001549 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001550 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001551 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001552 timestamped_message.data.span().size() != 0u) {
1553 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001554 << ": Got a message without data on channel "
1555 << configuration::CleanedChannelToString(
1556 logged_configuration()->channels()->Get(
1557 timestamped_message.channel_index))
1558 << ". Forwarding entry which was not matched? Use "
1559 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001560
Austin Schuh2f8fd752020-09-01 22:38:28 -07001561 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001562 // Confirm that the message was sent on the sending node before the
1563 // destination node (this node). As a proxy, do this by making sure
1564 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001565 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001566 CHECK_LT(
1567 timestamped_message.monotonic_remote_time,
1568 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001569 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001570 << state->remote_node(timestamped_message.channel_index)
1571 ->name()
1572 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001573 << " while trying to send a message on "
1574 << configuration::CleanedChannelToString(
1575 logged_configuration()->channels()->Get(
1576 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001577 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001578 } else if (timestamped_message.monotonic_remote_time >=
1579 state->monotonic_remote_now(
1580 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001581 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001582 << "Check failed: timestamped_message.monotonic_remote_time < "
1583 "state->monotonic_remote_now(timestamped_message.channel_"
1584 "index) ("
1585 << timestamped_message.monotonic_remote_time << " vs. "
1586 << state->monotonic_remote_now(
1587 timestamped_message.channel_index)
1588 << ") " << state->event_loop()->node()->name()->string_view()
1589 << " to "
1590 << state->remote_node(timestamped_message.channel_index)
1591 ->name()
1592 ->string_view()
1593 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001594 << " ("
1595 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001596 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001597 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001598 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001599 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001600 timestamped_message.channel_index,
1601 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001602 << ") " << state->DebugString();
1603 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001604
1605 if (FLAGS_timestamps_to_csv) {
1606 if (offset_fp_ == nullptr) {
1607 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1608 fprintf(
1609 offset_fp_,
1610 "# time_since_start, offset node 0, offset node 1, ...\n");
Austin Schuh287d43d2020-12-04 20:19:33 -08001611 first_time_ = timestamped_message.realtime_event_time;
Austin Schuh8bd96322020-02-13 21:18:22 -08001612 }
1613
1614 fprintf(offset_fp_, "%.9f",
1615 std::chrono::duration_cast<std::chrono::duration<double>>(
Austin Schuh287d43d2020-12-04 20:19:33 -08001616 timestamped_message.realtime_event_time - first_time_)
Austin Schuh8bd96322020-02-13 21:18:22 -08001617 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001618 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1619 fprintf(offset_fp_, ", %.9f",
1620 time_offset_matrix_(i, 0) +
1621 time_slope_matrix_(i, 0) *
1622 chrono::duration<double>(
1623 event_loop_factory_->distributed_now()
1624 .time_since_epoch())
1625 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001626 }
1627 fprintf(offset_fp_, "\n");
1628 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001629 }
1630
Austin Schuh15649d62019-12-28 16:36:38 -08001631 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001632 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1633 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001634
Austin Schuh2f8fd752020-09-01 22:38:28 -07001635 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001636 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001637 // TODO(austin): std::move channel_data in and make that efficient in
1638 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001639 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001640 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001641 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001642 // reading the rest of the log file and call it quits. We don't want
1643 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001644 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1645 bool update_time_dummy;
1646 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001647 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001648 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001649 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001650 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001651 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001652 LOG(WARNING)
1653 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001654 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001655 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001656 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001657 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001658 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001659 }
1660
Austin Schuh858c9f32020-08-31 16:56:12 -07001661 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001662 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001663 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1664 << "wakeup for " << next_time << "("
1665 << state->ToDistributedClock(next_time)
1666 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001667 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001668 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001669 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1670 << "No next message, scheduling shutdown";
1671 // Set a timer up immediately after now to die. If we don't do this,
1672 // then the senders waiting on the message we just read will never get
1673 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001674 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001675 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1676 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001677 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001678 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001679
Austin Schuh2f8fd752020-09-01 22:38:28 -07001680 // Once we make this call, the current time changes. So do everything
1681 // which involves time before changing it. That especially includes
1682 // sending the message.
1683 if (update_time) {
1684 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1685 << "updating offsets";
1686
1687 std::vector<aos::monotonic_clock::time_point> before_times;
1688 before_times.resize(states_.size());
1689 std::transform(states_.begin(), states_.end(), before_times.begin(),
1690 [](const std::unique_ptr<State> &state) {
1691 return state->monotonic_now();
1692 });
1693
1694 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001695 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1696 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001697 }
1698
Austin Schuh8bd96322020-02-13 21:18:22 -08001699 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001700 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1701 << state->monotonic_now();
1702
1703 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001704 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1705 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001706 }
1707
1708 // TODO(austin): We should be perfect.
1709 const std::chrono::nanoseconds kTolerance{3};
1710 if (!FLAGS_skip_order_validation) {
1711 CHECK_GE(next_time, state->monotonic_now())
1712 << ": Time skipped the next event.";
1713
1714 for (size_t i = 0; i < states_.size(); ++i) {
1715 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1716 << ": Time changed too much on node "
1717 << MaybeNodeName(states_[i]->event_loop()->node());
1718 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1719 << ": Time changed too much on node "
1720 << states_[i]->event_loop()->node()->name()->string_view();
1721 }
1722 } else {
1723 if (next_time < state->monotonic_now()) {
1724 LOG(WARNING) << "Check failed: next_time >= "
1725 "state->monotonic_now() ("
1726 << next_time << " vs. " << state->monotonic_now()
1727 << "): Time skipped the next event.";
1728 }
1729 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001730 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001731 LOG(WARNING) << "Check failed: "
1732 "states_[i]->monotonic_now() "
1733 ">= before_times[i] - kTolerance ("
1734 << states_[i]->monotonic_now() << " vs. "
1735 << before_times[i] - kTolerance
1736 << ") : Time changed too much on node "
1737 << MaybeNodeName(states_[i]->event_loop()->node());
1738 }
Austin Schuh724032b2020-12-18 22:54:59 -08001739 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001740 LOG(WARNING) << "Check failed: "
1741 "states_[i]->monotonic_now() "
1742 "<= before_times[i] + kTolerance ("
1743 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001744 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001745 << ") : Time changed too much on node "
1746 << MaybeNodeName(states_[i]->event_loop()->node());
1747 }
1748 }
1749 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001750 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001751
1752 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1753 << state->event_loop()->context().monotonic_event_time << " now "
1754 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001755 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001756
Austin Schuh6f3babe2020-01-26 20:34:50 -08001757 ++live_nodes_;
1758
Austin Schuh858c9f32020-08-31 16:56:12 -07001759 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1760 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001761 }
1762}
1763
1764void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001765 // Make sure that things get destroyed in the correct order, rather than
1766 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001767 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001768 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001769 }
Austin Schuh92547522019-12-28 14:33:43 -08001770
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001771 event_loop_factory_unique_ptr_.reset();
1772 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001773}
1774
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001775void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001776 std::string_view add_prefix,
1777 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001778 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1779 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1780 if (channel->name()->str() == name &&
1781 channel->type()->string_view() == type) {
1782 CHECK_EQ(0u, remapped_channels_.count(ii))
1783 << "Already remapped channel "
1784 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001785 RemappedChannel remapped_channel;
1786 remapped_channel.remapped_name =
1787 std::string(add_prefix) + std::string(name);
1788 remapped_channel.new_type = new_type;
1789 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001790 VLOG(1) << "Remapping channel "
1791 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001792 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001793 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001794 return;
1795 }
1796 }
1797 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1798 << type;
1799}
1800
Austin Schuh01b4c352020-09-21 23:09:39 -07001801void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1802 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001803 std::string_view add_prefix,
1804 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001805 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1806 const Channel *remapped_channel =
1807 configuration::GetChannel(logged_configuration(), name, type, "", node);
1808 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1809 << "\", \"type\": \"" << type << "\"}";
1810 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1811 << "\"}";
1812 VLOG(1) << "Remapped "
1813 << aos::configuration::StrippedChannelToString(remapped_channel);
1814
1815 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1816 // we want it to degrade if the heuristics fail to just work.
1817 //
1818 // The easiest way to do this is going to be incredibly specific and verbose.
1819 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1820 // /original/0/spray. Then, create a map from /original/spray to
1821 // /original/0/spray for just the type we were asked for.
1822 if (name != remapped_channel->name()->string_view()) {
1823 MapT new_map;
1824 new_map.match = std::make_unique<ChannelT>();
1825 new_map.match->name = absl::StrCat(add_prefix, name);
1826 new_map.match->type = type;
1827 if (node != nullptr) {
1828 new_map.match->source_node = node->name()->str();
1829 }
1830 new_map.rename = std::make_unique<ChannelT>();
1831 new_map.rename->name =
1832 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1833 maps_.emplace_back(std::move(new_map));
1834 }
1835
1836 const size_t channel_index =
1837 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1838 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1839 << "Already remapped channel "
1840 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001841
1842 RemappedChannel remapped_channel_struct;
1843 remapped_channel_struct.remapped_name =
1844 std::string(add_prefix) +
1845 std::string(remapped_channel->name()->string_view());
1846 remapped_channel_struct.new_type = new_type;
1847 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001848 MakeRemappedConfig();
1849}
1850
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001851void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001852 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001853 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001854 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001855 << ": Can't change the mapping after the events are scheduled.";
1856 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001857 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001858
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001859 // If no remapping occurred and we are using the original config, then there
1860 // is nothing interesting to do here.
1861 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001862 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001863 return;
1864 }
1865 // Config to copy Channel definitions from. Use the specified
1866 // replay_configuration_ if it has been provided.
1867 const Configuration *const base_config = replay_configuration_ == nullptr
1868 ? logged_configuration()
1869 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001870
1871 // Create a config with all the channels, but un-sorted/merged. Collect up
1872 // the schemas while we do this. Call MergeConfiguration to sort everything,
1873 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001874
1875 // This is the builder that we use for the config containing all the new
1876 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001877 flatbuffers::FlatBufferBuilder fbb;
1878 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001879 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001880
1881 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1882 << ": Merging logic needs to be updated when the number of channel "
1883 "fields changes.";
1884
1885 // List of schemas.
1886 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1887 // Make sure our new RemoteMessage schema is in there for old logs without it.
1888 schema_map.insert(std::make_pair(
1889 RemoteMessage::GetFullyQualifiedName(),
1890 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1891 message_bridge::RemoteMessageSchema()))));
1892
1893 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001894 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001895 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001896 base_config, logged_configuration()->channels()->Get(pair.first), "",
1897 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001898 channel_offsets.emplace_back(
1899 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001900 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001901
Austin Schuh0de30f32020-12-06 12:44:28 -08001902 // Now reconstruct the original channels, translating types as needed
1903 for (const Channel *c : *base_config->channels()) {
1904 // Search for a mapping channel.
1905 std::string_view new_type = "";
1906 for (auto &pair : remapped_channels_) {
1907 const Channel *const remapped_channel =
1908 logged_configuration()->channels()->Get(pair.first);
1909 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1910 remapped_channel->type()->string_view() == c->type()->string_view()) {
1911 new_type = pair.second.new_type;
1912 break;
1913 }
1914 }
1915
1916 // Copy everything over.
1917 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1918
1919 // Add the schema if it doesn't exist.
1920 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1921 CHECK(c->has_schema());
1922 schema_map.insert(std::make_pair(c->type()->string_view(),
1923 RecursiveCopyFlatBuffer(c->schema())));
1924 }
1925 }
1926
1927 // The MergeConfiguration API takes a vector, not a map. Convert.
1928 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1929 while (!schema_map.empty()) {
1930 schemas.emplace_back(std::move(schema_map.begin()->second));
1931 schema_map.erase(schema_map.begin());
1932 }
1933
1934 // Create the Configuration containing the new channels that we want to add.
1935 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1936 channels_offset =
1937 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1938
1939 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001940 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001941 if (base_config->maps()) {
1942 for (const Map *map : *base_config->maps()) {
1943 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1944 }
1945 }
1946
1947 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001948 for (const MapT &map : maps_) {
1949 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001950 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001951 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001952 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001953 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001954 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001955 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1956 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001957 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001958 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001959 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001960 match_builder.add_name(match_name_offset);
1961 match_builder.add_type(match_type_offset);
1962 if (!map.match->source_node.empty()) {
1963 match_builder.add_source_node(match_source_node_offset);
1964 }
1965 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1966
Austin Schuh0de30f32020-12-06 12:44:28 -08001967 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001968 rename_builder.add_name(rename_name_offset);
1969 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1970
Austin Schuh0de30f32020-12-06 12:44:28 -08001971 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001972 map_builder.add_match(match_offset);
1973 map_builder.add_rename(rename_offset);
1974 map_offsets.emplace_back(map_builder.Finish());
1975 }
1976
Austin Schuh0de30f32020-12-06 12:44:28 -08001977 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1978 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001979
Austin Schuh0de30f32020-12-06 12:44:28 -08001980 // And copy everything else over.
1981 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1982 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1983
1984 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1985 applications_offset =
1986 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1987
1988 // Now insert everything else in unmodified.
1989 ConfigurationBuilder configuration_builder(fbb);
1990 if (!channels_offset.IsNull()) {
1991 configuration_builder.add_channels(channels_offset);
1992 }
1993 if (!maps_offsets.IsNull()) {
1994 configuration_builder.add_maps(maps_offsets);
1995 }
1996 if (!nodes_offset.IsNull()) {
1997 configuration_builder.add_nodes(nodes_offset);
1998 }
1999 if (!applications_offset.IsNull()) {
2000 configuration_builder.add_applications(applications_offset);
2001 }
2002
2003 if (base_config->has_channel_storage_duration()) {
2004 configuration_builder.add_channel_storage_duration(
2005 base_config->channel_storage_duration());
2006 }
2007
2008 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
2009 << ": Merging logic needs to be updated when the number of configuration "
2010 "fields changes.";
2011
2012 fbb.Finish(configuration_builder.Finish());
2013
2014 // Clean it up and return it! By using MergeConfiguration here, we'll
2015 // actually get a deduplicated config for free too.
2016 FlatbufferDetachedBuffer<Configuration> new_merged_config =
2017 configuration::MergeConfiguration(
2018 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
2019
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002020 remapped_configuration_buffer_ =
2021 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08002022 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002023
2024 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08002025
2026 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08002027}
2028
Austin Schuh6f3babe2020-01-26 20:34:50 -08002029const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
2030 const Channel *channel) {
2031 std::string_view channel_name = channel->name()->string_view();
2032 std::string_view channel_type = channel->type()->string_view();
2033 const int channel_index =
2034 configuration::ChannelIndex(logged_configuration(), channel);
2035 // If the channel is remapped, find the correct channel name to use.
2036 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07002037 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08002038 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08002039 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08002040 }
2041
Austin Schuhee711052020-08-24 16:06:09 -07002042 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08002043 const Channel *remapped_channel = configuration::GetChannel(
2044 event_loop->configuration(), channel_name, channel_type,
2045 event_loop->name(), event_loop->node());
2046
2047 CHECK(remapped_channel != nullptr)
2048 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
2049 << channel_type << "\"} because it is not in the provided configuration.";
2050
2051 return remapped_channel;
2052}
2053
Austin Schuh287d43d2020-12-04 20:19:33 -08002054LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
2055 : timestamp_mapper_(std::move(timestamp_mapper)) {}
2056
2057void LogReader::State::AddPeer(State *peer) {
2058 if (timestamp_mapper_ && peer->timestamp_mapper_) {
2059 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
2060 }
2061}
Austin Schuh858c9f32020-08-31 16:56:12 -07002062
2063EventLoop *LogReader::State::SetNodeEventLoopFactory(
2064 NodeEventLoopFactory *node_event_loop_factory) {
2065 node_event_loop_factory_ = node_event_loop_factory;
2066 event_loop_unique_ptr_ =
2067 node_event_loop_factory_->MakeEventLoop("log_reader");
2068 return event_loop_unique_ptr_.get();
2069}
2070
2071void LogReader::State::SetChannelCount(size_t count) {
2072 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002073 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07002074 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002075 channel_source_state_.resize(count);
2076 factory_channel_index_.resize(count);
2077 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07002078}
2079
2080void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002081 size_t logged_channel_index, size_t factory_channel_index,
2082 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07002083 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08002084 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002085 channels_[logged_channel_index] = std::move(sender);
2086 filters_[logged_channel_index] = filter;
2087 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
2088
2089 if (source_state) {
2090 channel_source_state_[logged_channel_index] = source_state;
2091
2092 if (remote_timestamp_sender != nullptr) {
2093 source_state->queue_index_map_[logged_channel_index] =
2094 std::make_unique<std::vector<State::SentTimestamp>>();
2095 }
2096 }
2097
2098 factory_channel_index_[logged_channel_index] = factory_channel_index;
2099}
2100
Austin Schuh287d43d2020-12-04 20:19:33 -08002101bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
2102 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002103 uint32_t remote_queue_index = 0xffffffff;
2104
Austin Schuh287d43d2020-12-04 20:19:33 -08002105 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
2106 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
2107 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
2108 ->queue_index_map_[timestamped_message.channel_index]
2109 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002110
2111 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08002112 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
2113 search.realtime_event_time = timestamped_message.realtime_remote_time;
2114 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002115
2116 // Find the sent time if available.
2117 auto element = std::lower_bound(
2118 queue_index_map->begin(), queue_index_map->end(), search,
2119 [](SentTimestamp a, SentTimestamp b) {
2120 if (b.monotonic_event_time < a.monotonic_event_time) {
2121 return false;
2122 }
2123 if (b.monotonic_event_time > a.monotonic_event_time) {
2124 return true;
2125 }
2126
2127 if (b.queue_index < a.queue_index) {
2128 return false;
2129 }
2130 if (b.queue_index > a.queue_index) {
2131 return true;
2132 }
2133
2134 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
2135 return false;
2136 });
2137
2138 // TODO(austin): Be a bit more principled here, but we will want to do that
2139 // after the logger rewrite. We hit this when one node finishes, but the
2140 // other node isn't done yet. So there is no send time, but there is a
2141 // receive time.
2142 if (element != queue_index_map->end()) {
2143 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08002144 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002145 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08002146 timestamped_message.realtime_remote_time);
2147 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002148
2149 remote_queue_index = element->actual_queue_index;
2150 }
2151 }
2152
2153 // Send! Use the replayed queue index here instead of the logged queue index
2154 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08002155 const bool sent = sender->Send(
2156 timestamped_message.data.message().data()->Data(),
2157 timestamped_message.data.message().data()->size(),
2158 timestamped_message.monotonic_remote_time,
2159 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002160 if (!sent) return false;
2161
Austin Schuh287d43d2020-12-04 20:19:33 -08002162 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002163 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08002164 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
2165 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
2166 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002167 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08002168 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2169 timestamp);
2170 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2171 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08002172 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08002173 remote_timestamp_senders_[timestamped_message.channel_index]
2174 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002175
Austin Schuh315b96b2020-12-11 21:21:12 -08002176 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
2177 builder.fbb()->CreateString(event_loop_->boot_uuid().string_view());
2178
Austin Schuh0de30f32020-12-06 12:44:28 -08002179 RemoteMessage::Builder message_header_builder =
2180 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002181
2182 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002183 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002184
2185 // Swap the remote and sent metrics. They are from the sender's
2186 // perspective, not the receiver's perspective.
2187 message_header_builder.add_monotonic_sent_time(
2188 sender->monotonic_sent_time().time_since_epoch().count());
2189 message_header_builder.add_realtime_sent_time(
2190 sender->realtime_sent_time().time_since_epoch().count());
2191 message_header_builder.add_queue_index(sender->sent_queue_index());
2192
2193 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002194 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002195 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002196 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002197
2198 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002199 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002200
2201 builder.Send(message_header_builder.Finish());
2202 }
2203
2204 return true;
2205}
2206
Austin Schuh0de30f32020-12-06 12:44:28 -08002207aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002208 const Node *delivered_node) {
2209 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2210
2211 if (sender == remote_timestamp_senders_map_.end()) {
2212 sender = remote_timestamp_senders_map_
2213 .emplace(std::make_pair(
2214 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08002215 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002216 absl::StrCat("/aos/remote_timestamps/",
2217 delivered_node->name()->string_view()))))
2218 .first;
2219 }
2220
2221 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07002222}
2223
Austin Schuh287d43d2020-12-04 20:19:33 -08002224TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002225 CHECK_GT(sorted_messages_.size(), 0u);
2226
Austin Schuh287d43d2020-12-04 20:19:33 -08002227 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002228 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002229 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002230 << std::get<0>(result).monotonic_event_time;
2231 sorted_messages_.pop_front();
2232 SeedSortedMessages();
2233
Austin Schuh287d43d2020-12-04 20:19:33 -08002234 if (std::get<1>(result) != nullptr) {
2235 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002236 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2237 } else {
2238 *update_time = false;
2239 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002240 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002241}
2242
2243monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2244 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002245 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002246 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2247 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2248 }
2249
Austin Schuh287d43d2020-12-04 20:19:33 -08002250 TimestampedMessage *m =
2251 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2252 if (m == nullptr) {
2253 return monotonic_clock::max_time;
2254 }
2255 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002256}
2257
2258void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002259 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002260 const aos::monotonic_clock::time_point end_queue_time =
2261 (sorted_messages_.size() > 0
2262 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002263 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuh858c9f32020-08-31 16:56:12 -07002264 std::chrono::seconds(2);
2265
2266 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002267 TimestampedMessage *m = timestamp_mapper_->Front();
2268 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002269 return;
2270 }
2271 if (sorted_messages_.size() > 0) {
2272 // Stop placing sorted messages on the list once we have 2 seconds
2273 // queued up (but queue at least until the log starts.
2274 if (end_queue_time <
2275 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2276 return;
2277 }
2278 }
2279
Austin Schuh2f8fd752020-09-01 22:38:28 -07002280 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2281
Austin Schuh287d43d2020-12-04 20:19:33 -08002282 TimestampedMessage timestamped_message = std::move(*m);
2283 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002284
Austin Schuh2f8fd752020-09-01 22:38:28 -07002285 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002286 if (timestamped_message.monotonic_remote_time !=
2287 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002288 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002289 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002290
2291 CHECK(filter != nullptr);
2292
2293 // Call the correct method depending on if we are the forward or
2294 // reverse direction here.
2295 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002296 timestamped_message.monotonic_event_time,
2297 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002298 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002299 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002300 }
2301}
2302
2303void LogReader::State::Deregister() {
2304 for (size_t i = 0; i < channels_.size(); ++i) {
2305 channels_[i].reset();
2306 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002307 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002308 event_loop_unique_ptr_.reset();
2309 event_loop_ = nullptr;
2310 timer_handler_ = nullptr;
2311 node_event_loop_factory_ = nullptr;
2312}
2313
Austin Schuhe309d2a2019-11-29 13:25:21 -08002314} // namespace logger
2315} // namespace aos