blob: 134c202ef3575a0631fb2843b5a520968d182cd3 [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 Schuh288479d2019-12-18 19:47:52 -080018#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080019#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070020#include "aos/util/file.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080021#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070022#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080023
Austin Schuh15649d62019-12-28 16:36:38 -080024DEFINE_bool(skip_missing_forwarding_entries, false,
25 "If true, drop any forwarding entries with missing data. If "
26 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080027
Austin Schuh8bd96322020-02-13 21:18:22 -080028DEFINE_bool(timestamps_to_csv, false,
29 "If true, write all the time synchronization information to a set "
30 "of CSV files in /tmp/. This should only be needed when debugging "
31 "time synchronization.");
32
Austin Schuh2f8fd752020-09-01 22:38:28 -070033DEFINE_bool(skip_order_validation, false,
34 "If true, ignore any out of orderness in replay");
35
Austin Schuhe309d2a2019-11-29 13:25:21 -080036namespace aos {
37namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070038namespace {
39// Helper to safely read a header, or CHECK.
40FlatbufferVector<LogFileHeader> MaybeReadHeaderOrDie(
41 const std::vector<std::vector<std::string>> &filenames) {
42 CHECK_GE(filenames.size(), 1u) << ": Empty filenames list";
43 CHECK_GE(filenames[0].size(), 1u) << ": Empty filenames list";
44 return ReadHeader(filenames[0][0]);
45}
Austin Schuhe309d2a2019-11-29 13:25:21 -080046namespace chrono = std::chrono;
Austin Schuh0afc4d12020-10-19 11:42:04 -070047} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -080048
Brian Silverman1f345222020-09-24 21:14:48 -070049Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
50 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -080051 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -070052 configuration_(configuration),
Brian Silvermanae7c0332020-09-30 16:58:23 -070053 boot_uuid_(
54 util::ReadFileToStringOrDie("/proc/sys/kernel/random/boot_id")),
Austin Schuh0c297012020-09-16 18:41:59 -070055 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -070056 timer_handler_(event_loop_->AddTimer(
57 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -070058 server_statistics_fetcher_(
59 configuration::MultiNode(event_loop_->configuration())
60 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
61 "/aos")
62 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -070063 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070064
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070065 // Find all the nodes which are logging timestamps on our node. This may
66 // over-estimate if should_log is specified.
67 std::vector<const Node *> timestamp_logger_nodes =
68 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070069
70 std::map<const Channel *, const Node *> timestamp_logger_channels;
71
72 // Now that we have all the nodes accumulated, make remote timestamp loggers
73 // for them.
74 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070075 // Note: since we are doing a find using the event loop channel, we need to
76 // make sure this channel pointer is part of the event loop configuration,
77 // not configuration_. This only matters when configuration_ !=
78 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -070079 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070080 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -070081 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
82 logger::MessageHeader::GetFullyQualifiedName(), event_loop_->name(),
83 event_loop_->node());
84
85 CHECK(channel != nullptr)
86 << ": Remote timestamps are logged on "
87 << event_loop_->node()->name()->string_view()
88 << " but can't find channel /aos/remote_timestamps/"
89 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -070090 if (!should_log(channel)) {
91 continue;
92 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070093 timestamp_logger_channels.insert(std::make_pair(channel, node));
94 }
95
Brian Silvermand90905f2020-09-23 14:42:56 -070096 const size_t our_node_index =
97 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070098
Brian Silverman1f345222020-09-24 21:14:48 -070099 for (size_t channel_index = 0;
100 channel_index < configuration_->channels()->size(); ++channel_index) {
101 const Channel *const config_channel =
102 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700103 // The MakeRawFetcher method needs a channel which is in the event loop
104 // configuration() object, not the configuration_ object. Go look that up
105 // from the config.
106 const Channel *channel = aos::configuration::GetChannel(
107 event_loop_->configuration(), config_channel->name()->string_view(),
108 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700109 CHECK(channel != nullptr)
110 << ": Failed to look up channel "
111 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700112 if (!should_log(channel)) {
113 continue;
114 }
Austin Schuh0c297012020-09-16 18:41:59 -0700115
Austin Schuhe309d2a2019-11-29 13:25:21 -0800116 FetcherStruct fs;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700117 fs.node_index = our_node_index;
Brian Silverman1f345222020-09-24 21:14:48 -0700118 fs.channel_index = channel_index;
119 fs.channel = channel;
120
Austin Schuh6f3babe2020-01-26 20:34:50 -0800121 const bool is_local =
122 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
123
Austin Schuh15649d62019-12-28 16:36:38 -0800124 const bool is_readable =
125 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700126 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
127 channel, event_loop_->node());
128 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800129
Brian Silverman1f345222020-09-24 21:14:48 -0700130 bool log_delivery_times = false;
131 if (event_loop_->node() != nullptr) {
132 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
133 channel, event_loop_->node(), event_loop_->node());
134 }
Austin Schuh15649d62019-12-28 16:36:38 -0800135
Austin Schuh2f8fd752020-09-01 22:38:28 -0700136 // Now, detect a MessageHeader timestamp logger where we should just log the
137 // contents to a file directly.
138 const bool log_contents = timestamp_logger_channels.find(channel) !=
139 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700140
141 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800142 fs.fetcher = event_loop->MakeRawFetcher(channel);
143 VLOG(1) << "Logging channel "
144 << configuration::CleanedChannelToString(channel);
145
146 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800147 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700148 fs.wants_timestamp_writer = true;
Austin Schuh15649d62019-12-28 16:36:38 -0800149 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800150 if (log_message) {
151 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700152 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800153 if (!is_local) {
154 fs.log_type = LogType::kLogRemoteMessage;
155 }
156 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 if (log_contents) {
158 VLOG(1) << "Timestamp logger channel "
159 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700160 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
161 fs.wants_contents_writer = true;
Austin Schuh0c297012020-09-16 18:41:59 -0700162 fs.node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700163 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700164 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800165 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800166 }
Brian Silverman1f345222020-09-24 21:14:48 -0700167 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700168
169 // When we are logging remote timestamps, we need to be able to translate from
170 // the channel index that the event loop uses to the channel index in the
171 // config in the log file.
172 event_loop_to_logged_channel_index_.resize(
173 event_loop->configuration()->channels()->size(), -1);
174 for (size_t event_loop_channel_index = 0;
175 event_loop_channel_index <
176 event_loop->configuration()->channels()->size();
177 ++event_loop_channel_index) {
178 const Channel *event_loop_channel =
179 event_loop->configuration()->channels()->Get(event_loop_channel_index);
180
181 const Channel *logged_channel = aos::configuration::GetChannel(
182 configuration_, event_loop_channel->name()->string_view(),
183 event_loop_channel->type()->string_view(), "",
184 configuration::GetNode(configuration_, event_loop_->node()));
185
186 if (logged_channel != nullptr) {
187 event_loop_to_logged_channel_index_[event_loop_channel_index] =
188 configuration::ChannelIndex(configuration_, logged_channel);
189 }
190 }
Brian Silverman1f345222020-09-24 21:14:48 -0700191}
192
193Logger::~Logger() {
194 if (log_namer_) {
195 // If we are replaying a log file, or in simulation, we want to force the
196 // last bit of data to be logged. The easiest way to deal with this is to
197 // poll everything as we go to destroy the class, ie, shut down the logger,
198 // and write it to disk.
199 StopLogging(event_loop_->monotonic_now());
200 }
201}
202
Brian Silvermanae7c0332020-09-30 16:58:23 -0700203void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
204 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700205 CHECK(!log_namer_) << ": Already logging";
206 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700207 log_event_uuid_ = UUID::Random();
208 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700209 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
210
211 // We want to do as much work as possible before the initial Fetch. Time
212 // between that and actually starting to log opens up the possibility of
213 // falling off the end of the queue during that time.
214
215 for (FetcherStruct &f : fetchers_) {
216 if (f.wants_writer) {
217 f.writer = log_namer_->MakeWriter(f.channel);
218 }
219 if (f.wants_timestamp_writer) {
220 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
221 }
222 if (f.wants_contents_writer) {
223 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
224 f.channel, CHECK_NOTNULL(f.timestamp_node));
225 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800226 }
227
Brian Silverman1f345222020-09-24 21:14:48 -0700228 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700229 node_state_.resize(configuration::MultiNode(configuration_)
230 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700231 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800232
Austin Schuh2f8fd752020-09-01 22:38:28 -0700233 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700234 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800235
Austin Schuh2f8fd752020-09-01 22:38:28 -0700236 node_state_[node_index].log_file_header = MakeHeader(node);
237 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800238
Austin Schuh2f8fd752020-09-01 22:38:28 -0700239 // Grab data from each channel right before we declare the log file started
240 // so we can capture the latest message on each channel. This lets us have
241 // non periodic messages with configuration that now get logged.
242 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700243 const auto start = event_loop_->monotonic_now();
244 const bool got_new = f.fetcher->Fetch();
245 const auto end = event_loop_->monotonic_now();
246 RecordFetchResult(start, end, got_new, &f);
247
248 // If there is a message, we want to write it.
249 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700250 }
251
252 // Clear out any old timestamps in case we are re-starting logging.
253 for (size_t i = 0; i < node_state_.size(); ++i) {
254 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time);
255 }
256
257 WriteHeader();
258
259 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
260 << " start_time " << last_synchronized_time_;
261
262 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
263 polling_period_);
264}
265
Brian Silverman1f345222020-09-24 21:14:48 -0700266std::unique_ptr<LogNamer> Logger::StopLogging(
267 aos::monotonic_clock::time_point end_time) {
268 CHECK(log_namer_) << ": Not logging right now";
269
270 if (end_time != aos::monotonic_clock::min_time) {
271 LogUntil(end_time);
272 }
273 timer_handler_->Disable();
274
275 for (FetcherStruct &f : fetchers_) {
276 f.writer = nullptr;
277 f.timestamp_writer = nullptr;
278 f.contents_writer = nullptr;
279 }
280 node_state_.clear();
281
Brian Silvermanae7c0332020-09-30 16:58:23 -0700282 log_event_uuid_ = UUID::Zero();
283 log_start_uuid_ = std::string();
284
Brian Silverman1f345222020-09-24 21:14:48 -0700285 return std::move(log_namer_);
286}
287
Austin Schuhfa895892020-01-07 20:07:41 -0800288void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700289 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700290 server_statistics_fetcher_.Fetch();
291 }
292
293 aos::monotonic_clock::time_point monotonic_start_time =
294 event_loop_->monotonic_now();
295 aos::realtime_clock::time_point realtime_start_time =
296 event_loop_->realtime_now();
297
298 // We need to pick a point in time to declare the log file "started". This
299 // starts here. It needs to be after everything is fetched so that the
300 // fetchers are all pointed at the most recent message before the start
301 // time.
302 last_synchronized_time_ = monotonic_start_time;
303
Austin Schuh6f3babe2020-01-26 20:34:50 -0800304 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700305 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700306 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
307 realtime_start_time);
Austin Schuh64fab802020-09-09 22:47:47 -0700308 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800309 }
310}
Austin Schuh8bd96322020-02-13 21:18:22 -0800311
Austin Schuh2f8fd752020-09-01 22:38:28 -0700312void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700313 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700314 server_statistics_fetcher_.Fetch();
315 } else {
316 return;
317 }
318
319 if (server_statistics_fetcher_.get() == nullptr) {
320 return;
321 }
322
323 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700324 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700325 if (MaybeUpdateTimestamp(
326 node, node_index,
327 server_statistics_fetcher_.context().monotonic_event_time,
328 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh64fab802020-09-09 22:47:47 -0700329 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700330 }
331 }
332}
333
334void Logger::SetStartTime(size_t node_index,
335 aos::monotonic_clock::time_point monotonic_start_time,
336 aos::realtime_clock::time_point realtime_start_time) {
337 node_state_[node_index].monotonic_start_time = monotonic_start_time;
338 node_state_[node_index].realtime_start_time = realtime_start_time;
339 node_state_[node_index]
340 .log_file_header.mutable_message()
341 ->mutate_monotonic_start_time(
342 std::chrono::duration_cast<std::chrono::nanoseconds>(
343 monotonic_start_time.time_since_epoch())
344 .count());
345 if (node_state_[node_index]
346 .log_file_header.mutable_message()
347 ->has_realtime_start_time()) {
348 node_state_[node_index]
349 .log_file_header.mutable_message()
350 ->mutate_realtime_start_time(
351 std::chrono::duration_cast<std::chrono::nanoseconds>(
352 realtime_start_time.time_since_epoch())
353 .count());
354 }
355}
356
357bool Logger::MaybeUpdateTimestamp(
358 const Node *node, int node_index,
359 aos::monotonic_clock::time_point monotonic_start_time,
360 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700361 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700362 if (node_state_[node_index].monotonic_start_time !=
363 monotonic_clock::min_time) {
364 return false;
365 }
Austin Schuh0c297012020-09-16 18:41:59 -0700366 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700367 if (event_loop_->node() == node) {
368 // There are no offsets to compute for ourself, so always succeed.
369 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
370 return true;
371 } else if (server_statistics_fetcher_.get() != nullptr) {
372 // We must be a remote node now. Look for the connection and see if it is
373 // connected.
374
375 for (const message_bridge::ServerConnection *connection :
376 *server_statistics_fetcher_->connections()) {
377 if (connection->node()->name()->string_view() !=
378 node->name()->string_view()) {
379 continue;
380 }
381
382 if (connection->state() != message_bridge::State::CONNECTED) {
383 VLOG(1) << node->name()->string_view()
384 << " is not connected, can't start it yet.";
385 break;
386 }
387
388 if (!connection->has_monotonic_offset()) {
389 VLOG(1) << "Missing monotonic offset for setting start time for node "
390 << aos::FlatbufferToJson(node);
391 break;
392 }
393
394 VLOG(1) << "Updating start time for " << aos::FlatbufferToJson(node);
395
396 // Found it and it is connected. Compensate and go.
397 monotonic_start_time +=
398 std::chrono::nanoseconds(connection->monotonic_offset());
399
400 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
401 return true;
402 }
403 }
404 } else {
405 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
406 return true;
407 }
408 return false;
409}
410
411aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
412 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800413 // Now write the header with this timestamp in it.
414 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800415 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800416
Austin Schuh2f8fd752020-09-01 22:38:28 -0700417 // TODO(austin): Compress this much more efficiently. There are a bunch of
418 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700419 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700420 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800421
Brian Silvermanae7c0332020-09-30 16:58:23 -0700422 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700423 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800424
Brian Silvermanae7c0332020-09-30 16:58:23 -0700425 CHECK(log_event_uuid_ != UUID::Zero());
426 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
427 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700428
Brian Silvermanae7c0332020-09-30 16:58:23 -0700429 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
430 fbb.CreateString(logger_instance_uuid_.string_view());
431
432 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
433 if (!log_start_uuid_.empty()) {
434 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
435 }
436
437 const flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
438 fbb.CreateString(boot_uuid_);
439
440 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700441 fbb.CreateString("00000000-0000-4000-8000-000000000000");
442
Austin Schuhfa895892020-01-07 20:07:41 -0800443 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700444 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700445
Austin Schuh0c297012020-09-16 18:41:59 -0700446 if (configuration::MultiNode(configuration_)) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800447 node_offset = CopyFlatBuffer(node, &fbb);
Brian Silverman80993c22020-10-01 15:05:19 -0700448 logger_node_offset = CopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800449 }
450
451 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
452
Austin Schuh64fab802020-09-09 22:47:47 -0700453 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800454
455 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800456 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800457 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700458 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800459 }
460
461 log_file_header_builder.add_configuration(configuration_offset);
462 // The worst case theoretical out of order is the polling period times 2.
463 // One message could get logged right after the boundary, but be for right
464 // before the next boundary. And the reverse could happen for another
465 // message. Report back 3x to be extra safe, and because the cost isn't
466 // huge on the read side.
467 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700468 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800469
470 log_file_header_builder.add_monotonic_start_time(
471 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700472 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800473 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700474 if (node == event_loop_->node()) {
475 log_file_header_builder.add_realtime_start_time(
476 std::chrono::duration_cast<std::chrono::nanoseconds>(
477 realtime_clock::min_time.time_since_epoch())
478 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800479 }
480
Brian Silvermanae7c0332020-09-30 16:58:23 -0700481 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
482 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
483 if (!log_start_uuid_offset.IsNull()) {
484 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
485 }
486 log_file_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700487
488 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
489 log_file_header_builder.add_parts_index(0);
490
Austin Schuh2f8fd752020-09-01 22:38:28 -0700491 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
492 return fbb.Release();
493}
494
Brian Silvermancb805822020-10-06 17:43:35 -0700495void Logger::ResetStatisics() {
496 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
497 max_message_fetch_time_channel_ = -1;
498 max_message_fetch_time_size_ = -1;
499 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
500 total_message_fetch_count_ = 0;
501 total_message_fetch_bytes_ = 0;
502 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
503 total_nop_fetch_count_ = 0;
504 max_copy_time_ = std::chrono::nanoseconds::zero();
505 max_copy_time_channel_ = -1;
506 max_copy_time_size_ = -1;
507 total_copy_time_ = std::chrono::nanoseconds::zero();
508 total_copy_count_ = 0;
509 total_copy_bytes_ = 0;
510}
511
Austin Schuh2f8fd752020-09-01 22:38:28 -0700512void Logger::Rotate() {
513 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700514 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700515 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700516 }
517}
518
519void Logger::LogUntil(monotonic_clock::time_point t) {
520 WriteMissingTimestamps();
521
522 // Write each channel to disk, one at a time.
523 for (FetcherStruct &f : fetchers_) {
524 while (true) {
525 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700526 const auto start = event_loop_->monotonic_now();
527 const bool got_new = f.fetcher->FetchNext();
528 const auto end = event_loop_->monotonic_now();
529 RecordFetchResult(start, end, got_new, &f);
530 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700531 VLOG(2) << "No new data on "
532 << configuration::CleanedChannelToString(
533 f.fetcher->channel());
534 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700535 }
Brian Silvermancb805822020-10-06 17:43:35 -0700536 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700537 }
538
Austin Schuh2f8fd752020-09-01 22:38:28 -0700539 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700540 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700541 break;
542 }
Brian Silvermancb805822020-10-06 17:43:35 -0700543 if (f.writer != nullptr) {
544 // Write!
545 const auto start = event_loop_->monotonic_now();
546 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
547 max_header_size_);
548 fbb.ForceDefaults(true);
549
550 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
551 f.channel_index, f.log_type));
552 const auto end = event_loop_->monotonic_now();
553 RecordCreateMessageTime(start, end, &f);
554
555 VLOG(2) << "Writing data as node "
556 << FlatbufferToJson(event_loop_->node()) << " for channel "
557 << configuration::CleanedChannelToString(f.fetcher->channel())
558 << " to " << f.writer->filename() << " data "
559 << FlatbufferToJson(
560 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
561 fbb.GetBufferPointer()));
562
563 max_header_size_ = std::max(max_header_size_,
564 fbb.GetSize() - f.fetcher->context().size);
565 f.writer->QueueSizedFlatbuffer(&fbb);
566 }
567
568 if (f.timestamp_writer != nullptr) {
569 // And now handle timestamps.
570 const auto start = event_loop_->monotonic_now();
571 flatbuffers::FlatBufferBuilder fbb;
572 fbb.ForceDefaults(true);
573
574 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
575 f.channel_index,
576 LogType::kLogDeliveryTimeOnly));
577 const auto end = event_loop_->monotonic_now();
578 RecordCreateMessageTime(start, end, &f);
579
580 VLOG(2) << "Writing timestamps as node "
581 << FlatbufferToJson(event_loop_->node()) << " for channel "
582 << configuration::CleanedChannelToString(f.fetcher->channel())
583 << " to " << f.timestamp_writer->filename() << " timestamp "
584 << FlatbufferToJson(
585 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
586 fbb.GetBufferPointer()));
587
588 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
589 }
590
591 if (f.contents_writer != nullptr) {
592 const auto start = event_loop_->monotonic_now();
593 // And now handle the special message contents channel. Copy the
594 // message into a FlatBufferBuilder and save it to disk.
595 // TODO(austin): We can be more efficient here when we start to
596 // care...
597 flatbuffers::FlatBufferBuilder fbb;
598 fbb.ForceDefaults(true);
599
600 const MessageHeader *msg =
601 flatbuffers::GetRoot<MessageHeader>(f.fetcher->context().data);
602
603 logger::MessageHeader::Builder message_header_builder(fbb);
604
605 // TODO(austin): This needs to check the channel_index and confirm
606 // that it should be logged before squirreling away the timestamp to
607 // disk. We don't want to log irrelevant timestamps.
608
609 // Note: this must match the same order as MessageBridgeServer and
610 // PackMessage. We want identical headers to have identical
611 // on-the-wire formats to make comparing them easier.
612
613 // Translate from the channel index that the event loop uses to the
614 // channel index in the log file.
615 message_header_builder.add_channel_index(
616 event_loop_to_logged_channel_index_[msg->channel_index()]);
617
618 message_header_builder.add_queue_index(msg->queue_index());
619 message_header_builder.add_monotonic_sent_time(
620 msg->monotonic_sent_time());
621 message_header_builder.add_realtime_sent_time(
622 msg->realtime_sent_time());
623
624 message_header_builder.add_monotonic_remote_time(
625 msg->monotonic_remote_time());
626 message_header_builder.add_realtime_remote_time(
627 msg->realtime_remote_time());
628 message_header_builder.add_remote_queue_index(
629 msg->remote_queue_index());
630
631 fbb.FinishSizePrefixed(message_header_builder.Finish());
632 const auto end = event_loop_->monotonic_now();
633 RecordCreateMessageTime(start, end, &f);
634
635 f.contents_writer->QueueSizedFlatbuffer(&fbb);
636 }
637
638 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700639 }
640 }
641 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800642}
643
Brian Silverman1f345222020-09-24 21:14:48 -0700644void Logger::DoLogData(const monotonic_clock::time_point end_time) {
645 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800646 // max_out_of_order_duration. To do this, we need sync points. Every write
647 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800648
649 do {
650 // Move the sync point up by at most polling_period. This forces one sync
651 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700652 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
653
654 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800655
Austin Schuhe309d2a2019-11-29 13:25:21 -0800656 // If we missed cycles, we could be pretty far behind. Spin until we are
657 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700658 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800659}
660
Brian Silvermancb805822020-10-06 17:43:35 -0700661void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
662 aos::monotonic_clock::time_point end,
663 bool got_new, FetcherStruct *fetcher) {
664 const auto duration = end - start;
665 if (!got_new) {
666 ++total_nop_fetch_count_;
667 total_nop_fetch_time_ += duration;
668 return;
669 }
670 ++total_message_fetch_count_;
671 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
672 total_message_fetch_time_ += duration;
673 if (duration > max_message_fetch_time_) {
674 max_message_fetch_time_ = duration;
675 max_message_fetch_time_channel_ = fetcher->channel_index;
676 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
677 }
678}
679
680void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
681 aos::monotonic_clock::time_point end,
682 FetcherStruct *fetcher) {
683 const auto duration = end - start;
684 total_copy_time_ += duration;
685 ++total_copy_count_;
686 total_copy_bytes_ += fetcher->fetcher->context().size;
687 if (duration > max_copy_time_) {
688 max_copy_time_ = duration;
689 max_copy_time_channel_ = fetcher->channel_index;
690 max_copy_time_size_ = fetcher->fetcher->context().size;
691 }
692}
693
Austin Schuh11d43732020-09-21 17:28:30 -0700694std::vector<std::vector<std::string>> ToLogReaderVector(
695 const std::vector<LogFile> &log_files) {
696 std::vector<std::vector<std::string>> result;
697 for (const LogFile &log_file : log_files) {
698 for (const LogParts &log_parts : log_file.parts) {
699 std::vector<std::string> parts;
700 for (const std::string &part : log_parts.parts) {
701 parts.emplace_back(part);
702 }
703 result.emplace_back(std::move(parts));
704 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700705 }
706 return result;
707}
708
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800709LogReader::LogReader(std::string_view filename,
710 const Configuration *replay_configuration)
Austin Schuhfa895892020-01-07 20:07:41 -0800711 : LogReader(std::vector<std::string>{std::string(filename)},
712 replay_configuration) {}
713
714LogReader::LogReader(const std::vector<std::string> &filenames,
715 const Configuration *replay_configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800716 : LogReader(std::vector<std::vector<std::string>>{filenames},
717 replay_configuration) {}
718
Austin Schuh11d43732020-09-21 17:28:30 -0700719// TODO(austin): Make this the base and kill the others. This has much better
720// context for sorting.
721LogReader::LogReader(const std::vector<LogFile> &log_files,
722 const Configuration *replay_configuration)
723 : LogReader(ToLogReaderVector(log_files), replay_configuration) {}
724
Austin Schuh6f3babe2020-01-26 20:34:50 -0800725LogReader::LogReader(const std::vector<std::vector<std::string>> &filenames,
726 const Configuration *replay_configuration)
727 : filenames_(filenames),
Austin Schuh0afc4d12020-10-19 11:42:04 -0700728 log_file_header_(MaybeReadHeaderOrDie(filenames)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800729 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800730 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800731
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700732 // Remap all existing remote timestamp channels. They will be recreated, and
733 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700734 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700735 std::vector<const Node *> timestamp_logger_nodes =
736 configuration::TimestampNodes(logged_configuration(), node);
737 for (const Node *remote_node : timestamp_logger_nodes) {
738 const std::string channel = absl::StrCat(
739 "/aos/remote_timestamps/", remote_node->name()->string_view());
740 CHECK(HasChannel<logger::MessageHeader>(channel, node))
741 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
742 << logger::MessageHeader::GetFullyQualifiedName() << "\"} for node "
743 << node->name()->string_view();
744 RemapLoggedChannel<logger::MessageHeader>(channel, node);
745 }
746 }
747
Austin Schuh6aa77be2020-02-22 21:06:40 -0800748 if (replay_configuration) {
749 CHECK_EQ(configuration::MultiNode(configuration()),
750 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700751 << ": Log file and replay config need to both be multi or single "
752 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800753 }
754
Austin Schuh6f3babe2020-01-26 20:34:50 -0800755 if (!configuration::MultiNode(configuration())) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700756 states_.emplace_back(
757 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800758 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800759 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700760 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800761 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700762 << ": Log file and replay config need to have matching nodes "
763 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700764 for (const Node *node : *logged_configuration()->nodes()) {
765 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700766 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
767 << " in logged config that is not present in the replay "
768 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700769 }
770 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800771 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800772 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800773 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800774}
775
Austin Schuh6aa77be2020-02-22 21:06:40 -0800776LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700777 if (event_loop_factory_unique_ptr_) {
778 Deregister();
779 } else if (event_loop_factory_ != nullptr) {
780 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
781 "is destroyed";
782 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800783 if (offset_fp_ != nullptr) {
784 fclose(offset_fp_);
785 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700786 // Zero out some buffers. It's easy to do use-after-frees on these, so make
787 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700788 if (remapped_configuration_buffer_) {
789 remapped_configuration_buffer_->Wipe();
790 }
791 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -0800792}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800793
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800794const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800795 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800796}
797
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800798const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800799 return remapped_configuration_;
800}
801
Austin Schuh6f3babe2020-01-26 20:34:50 -0800802std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700803 // Because the Node pointer will only be valid if it actually points to
804 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800805 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800806 //
807 // Also, note, that when ever a map is changed, the nodes in here are
808 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800809 CHECK(remapped_configuration_ != nullptr)
810 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800811 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800812}
Austin Schuh15649d62019-12-28 16:36:38 -0800813
Austin Schuh11d43732020-09-21 17:28:30 -0700814monotonic_clock::time_point LogReader::monotonic_start_time(
815 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800816 State *state =
817 states_[configuration::GetNodeIndex(configuration(), node)].get();
818 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
819
Austin Schuh858c9f32020-08-31 16:56:12 -0700820 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800821}
822
Austin Schuh11d43732020-09-21 17:28:30 -0700823realtime_clock::time_point LogReader::realtime_start_time(
824 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800825 State *state =
826 states_[configuration::GetNodeIndex(configuration(), node)].get();
827 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
828
Austin Schuh858c9f32020-08-31 16:56:12 -0700829 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800830}
831
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800832void LogReader::Register() {
833 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800834 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800835 Register(event_loop_factory_unique_ptr_.get());
836}
837
Austin Schuh92547522019-12-28 14:33:43 -0800838void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800839 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700840 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -0800841
Brian Silvermand90905f2020-09-23 14:42:56 -0700842 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800843 const size_t node_index =
844 configuration::GetNodeIndex(configuration(), node);
Austin Schuh858c9f32020-08-31 16:56:12 -0700845 states_[node_index] =
846 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames_));
Austin Schuh8bd96322020-02-13 21:18:22 -0800847 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700848 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700849 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700850
851 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -0800852 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700853
854 // Register after making all the State objects so we can build references
855 // between them.
856 for (const Node *node : configuration::GetNodes(configuration())) {
857 const size_t node_index =
858 configuration::GetNodeIndex(configuration(), node);
859 State *state = states_[node_index].get();
860
861 Register(state->event_loop());
862 }
863
James Kuszmaul46d82582020-05-09 19:50:09 -0700864 if (live_nodes_ == 0) {
865 LOG(FATAL)
866 << "Don't have logs from any of the nodes in the replay config--are "
867 "you sure that the replay config matches the original config?";
868 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800869
Austin Schuh2f8fd752020-09-01 22:38:28 -0700870 // We need to now seed our per-node time offsets and get everything set up
871 // to run.
872 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -0800873
Austin Schuh8bd96322020-02-13 21:18:22 -0800874 // It is easiest to solve for per node offsets with a matrix rather than
875 // trying to solve the equations by hand. So let's get after it.
876 //
877 // Now, build up the map matrix.
878 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700879 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
880 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
881 filters_.size() + 1, num_nodes);
882 slope_matrix_ =
883 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
884 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800885
Austin Schuh2f8fd752020-09-01 22:38:28 -0700886 offset_matrix_ =
887 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
888 valid_matrix_ =
889 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
890 last_valid_matrix_ =
891 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -0800892
Austin Schuh2f8fd752020-09-01 22:38:28 -0700893 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
894 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -0800895
Austin Schuh2f8fd752020-09-01 22:38:28 -0700896 // All times should average out to the distributed clock.
897 for (int i = 0; i < map_matrix_.cols(); ++i) {
898 // 1/num_nodes.
899 map_matrix_(0, i) = mpq_class(1, num_nodes);
900 }
901 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800902
903 {
904 // Now, add the a - b -> sample elements.
905 size_t i = 1;
906 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700907 std::tuple<message_bridge::NoncausalOffsetEstimator>>
908 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800909 const Node *const node_a = std::get<0>(filter.first);
910 const Node *const node_b = std::get<1>(filter.first);
911
912 const size_t node_a_index =
913 configuration::GetNodeIndex(configuration(), node_a);
914 const size_t node_b_index =
915 configuration::GetNodeIndex(configuration(), node_b);
916
Austin Schuh2f8fd752020-09-01 22:38:28 -0700917 // -a
918 map_matrix_(i, node_a_index) = mpq_class(-1);
919 // +b
920 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800921
922 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -0700923 std::get<0>(filter.second)
924 .set_slope_pointer(&slope_matrix_(i, node_a_index));
925 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
926
927 valid_matrix_(i) = false;
928 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -0800929
930 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800931 }
932 }
933
Austin Schuh858c9f32020-08-31 16:56:12 -0700934 for (std::unique_ptr<State> &state : states_) {
935 state->SeedSortedMessages();
936 }
937
Austin Schuh2f8fd752020-09-01 22:38:28 -0700938 // Rank of the map matrix tells you if all the nodes are in communication
939 // with each other, which tells you if the offsets are observable.
940 const size_t connected_nodes =
941 Eigen::FullPivLU<
942 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
943 .rank();
944
945 // We don't need to support isolated nodes until someone has a real use
946 // case.
947 CHECK_EQ(connected_nodes, num_nodes)
948 << ": There is a node which isn't communicating with the rest.";
949
950 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -0800951 UpdateOffsets();
952
Austin Schuh2f8fd752020-09-01 22:38:28 -0700953 // We want to start the log file at the last start time of the log files
954 // from all the nodes. Compute how long each node's simulation needs to run
955 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800956 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800957
Austin Schuh2f8fd752020-09-01 22:38:28 -0700958 // TODO(austin): We want an "OnStart" callback for each node rather than
959 // running until the last node.
960
Austin Schuh8bd96322020-02-13 21:18:22 -0800961 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700962 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
963 << MaybeNodeName(state->event_loop()->node()) << "now "
964 << state->monotonic_now();
965 // And start computing the start time on the distributed clock now that
966 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -0700967 start_time = std::max(
968 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -0800969 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700970
971 CHECK_GE(start_time, distributed_clock::epoch())
972 << ": Hmm, we have a node starting before the start of time. Offset "
973 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -0800974
Austin Schuh6f3babe2020-01-26 20:34:50 -0800975 // Forwarding is tracked per channel. If it is enabled, we want to turn it
976 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700977 // nodes, and also replayed on the other nodes. This may not satisfy all
978 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800979 if (configuration::MultiNode(event_loop_factory_->configuration())) {
980 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
981 const Channel *channel = logged_configuration()->channels()->Get(i);
982 const Node *node = configuration::GetNode(
983 configuration(), channel->source_node()->string_view());
984
Austin Schuh8bd96322020-02-13 21:18:22 -0800985 State *state =
986 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800987
988 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -0700989 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800990
991 event_loop_factory_->DisableForwarding(remapped_channel);
992 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700993
994 // If we are replaying a log, we don't want a bunch of redundant messages
995 // from both the real message bridge and simulated message bridge.
996 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800997 }
998
Austin Schuhcde938c2020-02-02 17:30:07 -0800999 // While we are starting the system up, we might be relying on matching data
1000 // to timestamps on log files where the timestamp log file starts before the
1001 // data. In this case, it is reasonable to expect missing data.
1002 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001003 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001004 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001005 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001006 // Now that we are running for real, missing data means that the log file is
1007 // corrupted or went wrong.
1008 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001009
Austin Schuh8bd96322020-02-13 21:18:22 -08001010 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001011 // Make the RT clock be correct before handing it to the user.
1012 if (state->realtime_start_time() != realtime_clock::min_time) {
1013 state->SetRealtimeOffset(state->monotonic_start_time(),
1014 state->realtime_start_time());
1015 }
1016 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1017 << MaybeNodeName(state->event_loop()->node()) << "now "
1018 << state->monotonic_now();
1019 }
1020
1021 if (FLAGS_timestamps_to_csv) {
1022 for (std::pair<const std::tuple<const Node *, const Node *>,
1023 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1024 &filter : filters_) {
1025 const Node *const node_a = std::get<0>(filter.first);
1026 const Node *const node_b = std::get<1>(filter.first);
1027
1028 std::get<0>(filter.second)
1029 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1030 ->monotonic_now());
1031 std::get<0>(filter.second)
1032 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1033 ->monotonic_now());
1034 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001035 }
1036}
1037
Austin Schuh2f8fd752020-09-01 22:38:28 -07001038void LogReader::UpdateOffsets() {
1039 VLOG(2) << "Samples are " << offset_matrix_;
1040 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1041 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1042 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1043 "]");
1044 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1045 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1046
1047 size_t node_index = 0;
1048 for (std::unique_ptr<State> &state : states_) {
1049 state->SetDistributedOffset(offset(node_index), slope(node_index));
1050 VLOG(1) << "Offset for node " << node_index << " "
1051 << MaybeNodeName(state->event_loop()->node()) << "is "
1052 << aos::distributed_clock::time_point(offset(node_index))
1053 << " slope " << std::setprecision(9) << std::fixed
1054 << slope(node_index);
1055 ++node_index;
1056 }
1057
1058 if (VLOG_IS_ON(1)) {
1059 LogFit("Offset is");
1060 }
1061}
1062
1063void LogReader::LogFit(std::string_view prefix) {
1064 for (std::unique_ptr<State> &state : states_) {
1065 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1066 << state->monotonic_now() << " distributed "
1067 << event_loop_factory_->distributed_now();
1068 }
1069
1070 for (std::pair<const std::tuple<const Node *, const Node *>,
1071 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1072 filters_) {
1073 message_bridge::NoncausalOffsetEstimator *estimator =
1074 &std::get<0>(filter.second);
1075
1076 if (estimator->a_timestamps().size() == 0 &&
1077 estimator->b_timestamps().size() == 0) {
1078 continue;
1079 }
1080
1081 if (VLOG_IS_ON(1)) {
1082 estimator->LogFit(prefix);
1083 }
1084
1085 const Node *const node_a = std::get<0>(filter.first);
1086 const Node *const node_b = std::get<1>(filter.first);
1087
1088 const size_t node_a_index =
1089 configuration::GetNodeIndex(configuration(), node_a);
1090 const size_t node_b_index =
1091 configuration::GetNodeIndex(configuration(), node_b);
1092
1093 const double recovered_slope =
1094 slope(node_b_index) / slope(node_a_index) - 1.0;
1095 const int64_t recovered_offset =
1096 offset(node_b_index).count() - offset(node_a_index).count() *
1097 slope(node_b_index) /
1098 slope(node_a_index);
1099
1100 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1101 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1102 << " offset " << std::setprecision(20) << recovered_offset
1103 << " (error "
1104 << recovered_offset - estimator->fit().offset().count() << ")";
1105
1106 const aos::distributed_clock::time_point a0 =
1107 states_[node_a_index]->ToDistributedClock(
1108 std::get<0>(estimator->a_timestamps()[0]));
1109 const aos::distributed_clock::time_point a1 =
1110 states_[node_a_index]->ToDistributedClock(
1111 std::get<0>(estimator->a_timestamps()[1]));
1112
1113 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1114 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1115 << " distributed -> " << node_b->name()->string_view() << " "
1116 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1117 << aos::monotonic_clock::time_point(
1118 std::chrono::nanoseconds(static_cast<int64_t>(
1119 std::get<0>(estimator->a_timestamps()[0])
1120 .time_since_epoch()
1121 .count() *
1122 (1.0 + estimator->fit().slope()))) +
1123 estimator->fit().offset())
1124 << ((a0 <= event_loop_factory_->distributed_now())
1125 ? ""
1126 : " After now, investigate");
1127 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1128 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1129 << " distributed -> " << node_b->name()->string_view() << " "
1130 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1131 << aos::monotonic_clock::time_point(
1132 std::chrono::nanoseconds(static_cast<int64_t>(
1133 std::get<0>(estimator->a_timestamps()[1])
1134 .time_since_epoch()
1135 .count() *
1136 (1.0 + estimator->fit().slope()))) +
1137 estimator->fit().offset())
1138 << ((event_loop_factory_->distributed_now() <= a1)
1139 ? ""
1140 : " Before now, investigate");
1141
1142 const aos::distributed_clock::time_point b0 =
1143 states_[node_b_index]->ToDistributedClock(
1144 std::get<0>(estimator->b_timestamps()[0]));
1145 const aos::distributed_clock::time_point b1 =
1146 states_[node_b_index]->ToDistributedClock(
1147 std::get<0>(estimator->b_timestamps()[1]));
1148
1149 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1150 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1151 << " distributed -> " << node_a->name()->string_view() << " "
1152 << states_[node_a_index]->FromDistributedClock(b0)
1153 << ((b0 <= event_loop_factory_->distributed_now())
1154 ? ""
1155 : " After now, investigate");
1156 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1157 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1158 << " distributed -> " << node_a->name()->string_view() << " "
1159 << states_[node_a_index]->FromDistributedClock(b1)
1160 << ((event_loop_factory_->distributed_now() <= b1)
1161 ? ""
1162 : " Before now, investigate");
1163 }
1164}
1165
1166message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001167 const Node *node_a, const Node *node_b) {
1168 CHECK_NE(node_a, node_b);
1169 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1170 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1171
1172 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001173 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001174 }
1175
1176 auto tuple = std::make_tuple(node_a, node_b);
1177
1178 auto it = filters_.find(tuple);
1179
1180 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001181 auto &x =
1182 filters_
1183 .insert(std::make_pair(
1184 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1185 node_a, node_b))))
1186 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001187 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001188 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1189 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1190 node_b->name()->string_view()));
1191 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1192 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1193 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001194 }
1195
Austin Schuh2f8fd752020-09-01 22:38:28 -07001196 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001197 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001198 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001199 }
1200}
1201
Austin Schuhe309d2a2019-11-29 13:25:21 -08001202void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001203 State *state =
1204 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1205 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001206
Austin Schuh858c9f32020-08-31 16:56:12 -07001207 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001208
Tyler Chatow67ddb032020-01-12 14:30:04 -08001209 // We don't run timing reports when trying to print out logged data, because
1210 // otherwise we would end up printing out the timing reports themselves...
1211 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001212 event_loop->SkipTimingReport();
1213 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001214
Austin Schuh858c9f32020-08-31 16:56:12 -07001215 const bool has_data = state->SetNode();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001216
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001217 for (size_t logged_channel_index = 0;
1218 logged_channel_index < logged_configuration()->channels()->size();
1219 ++logged_channel_index) {
1220 const Channel *channel = RemapChannel(
1221 event_loop,
1222 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001223
Austin Schuh2f8fd752020-09-01 22:38:28 -07001224 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001225 aos::Sender<MessageHeader> *remote_timestamp_sender = nullptr;
1226
1227 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001228
1229 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1230 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001231 // We've got a message which is being forwarded to this node.
1232 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001233 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001234 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001235
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001236 // Delivery timestamps are supposed to be logged back on the source node.
1237 // Configure remote timestamps to be sent.
1238 const bool delivery_time_is_logged =
1239 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1240 channel, event_loop->node(), source_node);
1241
1242 source_state =
1243 states_[configuration::GetNodeIndex(configuration(), source_node)]
1244 .get();
1245
1246 if (delivery_time_is_logged) {
1247 remote_timestamp_sender =
1248 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001249 }
1250 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001251
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001252 state->SetChannel(
1253 logged_channel_index,
1254 configuration::ChannelIndex(event_loop->configuration(), channel),
1255 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1256 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001257 }
1258
Austin Schuh6aa77be2020-02-22 21:06:40 -08001259 // If we didn't find any log files with data in them, we won't ever get a
1260 // callback or be live. So skip the rest of the setup.
1261 if (!has_data) {
1262 return;
1263 }
1264
Austin Schuh858c9f32020-08-31 16:56:12 -07001265 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001266 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1267 << "at " << state->event_loop()->context().monotonic_event_time
1268 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001269 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001270 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001271 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001272 if (live_nodes_ == 0) {
1273 event_loop_factory_->Exit();
1274 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001275 return;
1276 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001277 TimestampMerger::DeliveryTimestamp channel_timestamp;
Austin Schuh05b70472020-01-01 17:11:17 -08001278 int channel_index;
1279 FlatbufferVector<MessageHeader> channel_data =
1280 FlatbufferVector<MessageHeader>::Empty();
1281
Austin Schuh2f8fd752020-09-01 22:38:28 -07001282 if (VLOG_IS_ON(1)) {
1283 LogFit("Offset was");
1284 }
1285
1286 bool update_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001287 std::tie(channel_timestamp, channel_index, channel_data) =
Austin Schuh2f8fd752020-09-01 22:38:28 -07001288 state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001289
Austin Schuhe309d2a2019-11-29 13:25:21 -08001290 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001291 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001292 if (!FLAGS_skip_order_validation) {
1293 CHECK(monotonic_now == channel_timestamp.monotonic_event_time)
1294 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1295 << monotonic_now << " trying to send "
1296 << channel_timestamp.monotonic_event_time << " failure "
1297 << state->DebugString();
1298 } else if (monotonic_now != channel_timestamp.monotonic_event_time) {
1299 LOG(WARNING) << "Check failed: monotonic_now == "
1300 "channel_timestamp.monotonic_event_time) ("
1301 << monotonic_now << " vs. "
1302 << channel_timestamp.monotonic_event_time
1303 << "): " << FlatbufferToJson(state->event_loop()->node())
1304 << " Now " << monotonic_now << " trying to send "
1305 << channel_timestamp.monotonic_event_time << " failure "
1306 << state->DebugString();
1307 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001308
Austin Schuh6f3babe2020-01-26 20:34:50 -08001309 if (channel_timestamp.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001310 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001311 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001312 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001313 !state->at_end()) ||
Austin Schuh05b70472020-01-01 17:11:17 -08001314 channel_data.message().data() != nullptr) {
1315 CHECK(channel_data.message().data() != nullptr)
1316 << ": Got a message without data. Forwarding entry which was "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001317 "not matched? Use --skip_missing_forwarding_entries to "
Brian Silverman87ac0402020-09-17 14:47:01 -07001318 "ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001319
Austin Schuh2f8fd752020-09-01 22:38:28 -07001320 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001321 // Confirm that the message was sent on the sending node before the
1322 // destination node (this node). As a proxy, do this by making sure
1323 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001324 if (!FLAGS_skip_order_validation) {
1325 CHECK_LT(channel_timestamp.monotonic_remote_time,
1326 state->monotonic_remote_now(channel_index))
1327 << state->event_loop()->node()->name()->string_view() << " to "
1328 << state->remote_node(channel_index)->name()->string_view()
1329 << " " << state->DebugString();
1330 } else if (channel_timestamp.monotonic_remote_time >=
1331 state->monotonic_remote_now(channel_index)) {
1332 LOG(WARNING)
1333 << "Check failed: channel_timestamp.monotonic_remote_time < "
1334 "state->monotonic_remote_now(channel_index) ("
1335 << channel_timestamp.monotonic_remote_time << " vs. "
1336 << state->monotonic_remote_now(channel_index) << ") "
1337 << state->event_loop()->node()->name()->string_view() << " to "
1338 << state->remote_node(channel_index)->name()->string_view()
1339 << " currently " << channel_timestamp.monotonic_event_time
1340 << " ("
1341 << state->ToDistributedClock(
1342 channel_timestamp.monotonic_event_time)
1343 << ") remote event time "
1344 << channel_timestamp.monotonic_remote_time << " ("
1345 << state->RemoteToDistributedClock(
1346 channel_index, channel_timestamp.monotonic_remote_time)
1347 << ") " << state->DebugString();
1348 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001349
1350 if (FLAGS_timestamps_to_csv) {
1351 if (offset_fp_ == nullptr) {
1352 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1353 fprintf(
1354 offset_fp_,
1355 "# time_since_start, offset node 0, offset node 1, ...\n");
1356 first_time_ = channel_timestamp.realtime_event_time;
1357 }
1358
1359 fprintf(offset_fp_, "%.9f",
1360 std::chrono::duration_cast<std::chrono::duration<double>>(
1361 channel_timestamp.realtime_event_time - first_time_)
1362 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001363 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1364 fprintf(offset_fp_, ", %.9f",
1365 time_offset_matrix_(i, 0) +
1366 time_slope_matrix_(i, 0) *
1367 chrono::duration<double>(
1368 event_loop_factory_->distributed_now()
1369 .time_since_epoch())
1370 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001371 }
1372 fprintf(offset_fp_, "\n");
1373 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001374 }
1375
Austin Schuh15649d62019-12-28 16:36:38 -08001376 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh858c9f32020-08-31 16:56:12 -07001377 state->SetRealtimeOffset(channel_timestamp.monotonic_event_time,
1378 channel_timestamp.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001379
Austin Schuh2f8fd752020-09-01 22:38:28 -07001380 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
1381 << channel_timestamp.monotonic_event_time;
1382 // TODO(austin): std::move channel_data in and make that efficient in
1383 // simulation.
Austin Schuh858c9f32020-08-31 16:56:12 -07001384 state->Send(channel_index, channel_data.message().data()->Data(),
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001385 channel_data.message().data()->size(), channel_timestamp);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001386 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001387 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001388 // reading the rest of the log file and call it quits. We don't want
1389 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001390 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1391 bool update_time_dummy;
1392 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001393 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001394 } else {
1395 CHECK(channel_data.message().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001396 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001397 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001398 LOG(WARNING)
1399 << "Not sending data from before the start of the log file. "
1400 << channel_timestamp.monotonic_event_time.time_since_epoch().count()
1401 << " start " << monotonic_start_time().time_since_epoch().count()
1402 << " " << FlatbufferToJson(channel_data);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001403 }
1404
Austin Schuh858c9f32020-08-31 16:56:12 -07001405 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001406 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001407 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1408 << "wakeup for " << next_time << "("
1409 << state->ToDistributedClock(next_time)
1410 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001411 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001412 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001413 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1414 << "No next message, scheduling shutdown";
1415 // Set a timer up immediately after now to die. If we don't do this,
1416 // then the senders waiting on the message we just read will never get
1417 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001418 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001419 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1420 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001421 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001422 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001423
Austin Schuh2f8fd752020-09-01 22:38:28 -07001424 // Once we make this call, the current time changes. So do everything
1425 // which involves time before changing it. That especially includes
1426 // sending the message.
1427 if (update_time) {
1428 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1429 << "updating offsets";
1430
1431 std::vector<aos::monotonic_clock::time_point> before_times;
1432 before_times.resize(states_.size());
1433 std::transform(states_.begin(), states_.end(), before_times.begin(),
1434 [](const std::unique_ptr<State> &state) {
1435 return state->monotonic_now();
1436 });
1437
1438 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001439 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1440 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001441 }
1442
Austin Schuh8bd96322020-02-13 21:18:22 -08001443 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001444 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1445 << state->monotonic_now();
1446
1447 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001448 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1449 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001450 }
1451
1452 // TODO(austin): We should be perfect.
1453 const std::chrono::nanoseconds kTolerance{3};
1454 if (!FLAGS_skip_order_validation) {
1455 CHECK_GE(next_time, state->monotonic_now())
1456 << ": Time skipped the next event.";
1457
1458 for (size_t i = 0; i < states_.size(); ++i) {
1459 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1460 << ": Time changed too much on node "
1461 << MaybeNodeName(states_[i]->event_loop()->node());
1462 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1463 << ": Time changed too much on node "
1464 << states_[i]->event_loop()->node()->name()->string_view();
1465 }
1466 } else {
1467 if (next_time < state->monotonic_now()) {
1468 LOG(WARNING) << "Check failed: next_time >= "
1469 "state->monotonic_now() ("
1470 << next_time << " vs. " << state->monotonic_now()
1471 << "): Time skipped the next event.";
1472 }
1473 for (size_t i = 0; i < states_.size(); ++i) {
1474 if (states_[i]->monotonic_now() >= before_times[i] - kTolerance) {
1475 LOG(WARNING) << "Check failed: "
1476 "states_[i]->monotonic_now() "
1477 ">= before_times[i] - kTolerance ("
1478 << states_[i]->monotonic_now() << " vs. "
1479 << before_times[i] - kTolerance
1480 << ") : Time changed too much on node "
1481 << MaybeNodeName(states_[i]->event_loop()->node());
1482 }
1483 if (states_[i]->monotonic_now() <= before_times[i] + kTolerance) {
1484 LOG(WARNING) << "Check failed: "
1485 "states_[i]->monotonic_now() "
1486 "<= before_times[i] + kTolerance ("
1487 << states_[i]->monotonic_now() << " vs. "
1488 << before_times[i] - kTolerance
1489 << ") : Time changed too much on node "
1490 << MaybeNodeName(states_[i]->event_loop()->node());
1491 }
1492 }
1493 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001494 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001495
1496 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1497 << state->event_loop()->context().monotonic_event_time << " now "
1498 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001499 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001500
Austin Schuh6f3babe2020-01-26 20:34:50 -08001501 ++live_nodes_;
1502
Austin Schuh858c9f32020-08-31 16:56:12 -07001503 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1504 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001505 }
1506}
1507
1508void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001509 // Make sure that things get destroyed in the correct order, rather than
1510 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001511 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001512 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001513 }
Austin Schuh92547522019-12-28 14:33:43 -08001514
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001515 event_loop_factory_unique_ptr_.reset();
1516 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001517}
1518
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001519void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1520 std::string_view add_prefix) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001521 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1522 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1523 if (channel->name()->str() == name &&
1524 channel->type()->string_view() == type) {
1525 CHECK_EQ(0u, remapped_channels_.count(ii))
1526 << "Already remapped channel "
1527 << configuration::CleanedChannelToString(channel);
1528 remapped_channels_[ii] = std::string(add_prefix) + std::string(name);
1529 VLOG(1) << "Remapping channel "
1530 << configuration::CleanedChannelToString(channel)
1531 << " to have name " << remapped_channels_[ii];
Austin Schuh6331ef92020-01-07 18:28:09 -08001532 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001533 return;
1534 }
1535 }
1536 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1537 << type;
1538}
1539
Austin Schuh01b4c352020-09-21 23:09:39 -07001540void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1541 const Node *node,
1542 std::string_view add_prefix) {
1543 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1544 const Channel *remapped_channel =
1545 configuration::GetChannel(logged_configuration(), name, type, "", node);
1546 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1547 << "\", \"type\": \"" << type << "\"}";
1548 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1549 << "\"}";
1550 VLOG(1) << "Remapped "
1551 << aos::configuration::StrippedChannelToString(remapped_channel);
1552
1553 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1554 // we want it to degrade if the heuristics fail to just work.
1555 //
1556 // The easiest way to do this is going to be incredibly specific and verbose.
1557 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1558 // /original/0/spray. Then, create a map from /original/spray to
1559 // /original/0/spray for just the type we were asked for.
1560 if (name != remapped_channel->name()->string_view()) {
1561 MapT new_map;
1562 new_map.match = std::make_unique<ChannelT>();
1563 new_map.match->name = absl::StrCat(add_prefix, name);
1564 new_map.match->type = type;
1565 if (node != nullptr) {
1566 new_map.match->source_node = node->name()->str();
1567 }
1568 new_map.rename = std::make_unique<ChannelT>();
1569 new_map.rename->name =
1570 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1571 maps_.emplace_back(std::move(new_map));
1572 }
1573
1574 const size_t channel_index =
1575 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1576 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1577 << "Already remapped channel "
1578 << configuration::CleanedChannelToString(remapped_channel);
1579 remapped_channels_[channel_index] =
1580 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1581 MakeRemappedConfig();
1582}
1583
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001584void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001585 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001586 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001587 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001588 << ": Can't change the mapping after the events are scheduled.";
1589 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001590 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001591
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001592 // If no remapping occurred and we are using the original config, then there
1593 // is nothing interesting to do here.
1594 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001595 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001596 return;
1597 }
1598 // Config to copy Channel definitions from. Use the specified
1599 // replay_configuration_ if it has been provided.
1600 const Configuration *const base_config = replay_configuration_ == nullptr
1601 ? logged_configuration()
1602 : replay_configuration_;
1603 // The remapped config will be identical to the base_config, except that it
1604 // will have a bunch of extra channels in the channel list, which are exact
1605 // copies of the remapped channels, but with different names.
1606 // Because the flatbuffers API is a pain to work with, this requires a bit of
1607 // a song-and-dance to get copied over.
1608 // The order of operations is to:
1609 // 1) Make a flatbuffer builder for a config that will just contain a list of
1610 // the new channels that we want to add.
1611 // 2) For each channel that we are remapping:
1612 // a) Make a buffer/builder and construct into it a Channel table that only
1613 // contains the new name for the channel.
1614 // b) Merge the new channel with just the name into the channel that we are
1615 // trying to copy, built in the flatbuffer builder made in 1. This gives
1616 // us the new channel definition that we need.
1617 // 3) Using this list of offsets, build the Configuration of just new
1618 // Channels.
1619 // 4) Merge the Configuration with the new Channels into the base_config.
1620 // 5) Call MergeConfiguration() on that result to give MergeConfiguration a
1621 // chance to sanitize the config.
1622
1623 // This is the builder that we use for the config containing all the new
1624 // channels.
1625 flatbuffers::FlatBufferBuilder new_config_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001626 new_config_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001627 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
1628 for (auto &pair : remapped_channels_) {
1629 // This is the builder that we use for creating the Channel with just the
1630 // new name.
1631 flatbuffers::FlatBufferBuilder new_name_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001632 new_name_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001633 const flatbuffers::Offset<flatbuffers::String> name_offset =
1634 new_name_fbb.CreateString(pair.second);
1635 ChannelBuilder new_name_builder(new_name_fbb);
1636 new_name_builder.add_name(name_offset);
1637 new_name_fbb.Finish(new_name_builder.Finish());
1638 const FlatbufferDetachedBuffer<Channel> new_name = new_name_fbb.Release();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001639 // Retrieve the channel that we want to copy, confirming that it is
1640 // actually present in base_config.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001641 const Channel *const base_channel = CHECK_NOTNULL(configuration::GetChannel(
1642 base_config, logged_configuration()->channels()->Get(pair.first), "",
1643 nullptr));
1644 // Actually create the new channel and put it into the vector of Offsets
1645 // that we will use to create the new Configuration.
1646 channel_offsets.emplace_back(MergeFlatBuffers<Channel>(
1647 reinterpret_cast<const flatbuffers::Table *>(base_channel),
1648 reinterpret_cast<const flatbuffers::Table *>(&new_name.message()),
1649 &new_config_fbb));
1650 }
1651 // Create the Configuration containing the new channels that we want to add.
Austin Schuh01b4c352020-09-21 23:09:39 -07001652 const auto new_channel_vector_offsets =
Austin Schuhfa895892020-01-07 20:07:41 -08001653 new_config_fbb.CreateVector(channel_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001654
1655 // Now create the new maps.
1656 std::vector<flatbuffers::Offset<Map>> map_offsets;
1657 for (const MapT &map : maps_) {
1658 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
1659 new_config_fbb.CreateString(map.match->name);
1660 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
1661 new_config_fbb.CreateString(map.match->type);
1662 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1663 new_config_fbb.CreateString(map.rename->name);
1664 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1665 if (!map.match->source_node.empty()) {
1666 match_source_node_offset =
1667 new_config_fbb.CreateString(map.match->source_node);
1668 }
1669 Channel::Builder match_builder(new_config_fbb);
1670 match_builder.add_name(match_name_offset);
1671 match_builder.add_type(match_type_offset);
1672 if (!map.match->source_node.empty()) {
1673 match_builder.add_source_node(match_source_node_offset);
1674 }
1675 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1676
1677 Channel::Builder rename_builder(new_config_fbb);
1678 rename_builder.add_name(rename_name_offset);
1679 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1680
1681 Map::Builder map_builder(new_config_fbb);
1682 map_builder.add_match(match_offset);
1683 map_builder.add_rename(rename_offset);
1684 map_offsets.emplace_back(map_builder.Finish());
1685 }
1686
1687 const auto new_maps_offsets = new_config_fbb.CreateVector(map_offsets);
1688
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001689 ConfigurationBuilder new_config_builder(new_config_fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001690 new_config_builder.add_channels(new_channel_vector_offsets);
1691 new_config_builder.add_maps(new_maps_offsets);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001692 new_config_fbb.Finish(new_config_builder.Finish());
1693 const FlatbufferDetachedBuffer<Configuration> new_name_config =
1694 new_config_fbb.Release();
1695 // Merge the new channels configuration into the base_config, giving us the
1696 // remapped configuration.
1697 remapped_configuration_buffer_ =
1698 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1699 MergeFlatBuffers<Configuration>(base_config,
1700 &new_name_config.message()));
1701 // Call MergeConfiguration to deal with sanitizing the config.
1702 remapped_configuration_buffer_ =
1703 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1704 configuration::MergeConfiguration(*remapped_configuration_buffer_));
1705
1706 remapped_configuration_ = &remapped_configuration_buffer_->message();
1707}
1708
Austin Schuh6f3babe2020-01-26 20:34:50 -08001709const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1710 const Channel *channel) {
1711 std::string_view channel_name = channel->name()->string_view();
1712 std::string_view channel_type = channel->type()->string_view();
1713 const int channel_index =
1714 configuration::ChannelIndex(logged_configuration(), channel);
1715 // If the channel is remapped, find the correct channel name to use.
1716 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001717 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001718 << configuration::CleanedChannelToString(channel);
1719 channel_name = remapped_channels_[channel_index];
1720 }
1721
Austin Schuhee711052020-08-24 16:06:09 -07001722 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001723 const Channel *remapped_channel = configuration::GetChannel(
1724 event_loop->configuration(), channel_name, channel_type,
1725 event_loop->name(), event_loop->node());
1726
1727 CHECK(remapped_channel != nullptr)
1728 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1729 << channel_type << "\"} because it is not in the provided configuration.";
1730
1731 return remapped_channel;
1732}
1733
Austin Schuh858c9f32020-08-31 16:56:12 -07001734LogReader::State::State(std::unique_ptr<ChannelMerger> channel_merger)
1735 : channel_merger_(std::move(channel_merger)) {}
1736
1737EventLoop *LogReader::State::SetNodeEventLoopFactory(
1738 NodeEventLoopFactory *node_event_loop_factory) {
1739 node_event_loop_factory_ = node_event_loop_factory;
1740 event_loop_unique_ptr_ =
1741 node_event_loop_factory_->MakeEventLoop("log_reader");
1742 return event_loop_unique_ptr_.get();
1743}
1744
1745void LogReader::State::SetChannelCount(size_t count) {
1746 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001747 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001748 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001749 channel_source_state_.resize(count);
1750 factory_channel_index_.resize(count);
1751 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001752}
1753
1754void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001755 size_t logged_channel_index, size_t factory_channel_index,
1756 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001757 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001758 aos::Sender<MessageHeader> *remote_timestamp_sender, State *source_state) {
1759 channels_[logged_channel_index] = std::move(sender);
1760 filters_[logged_channel_index] = filter;
1761 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1762
1763 if (source_state) {
1764 channel_source_state_[logged_channel_index] = source_state;
1765
1766 if (remote_timestamp_sender != nullptr) {
1767 source_state->queue_index_map_[logged_channel_index] =
1768 std::make_unique<std::vector<State::SentTimestamp>>();
1769 }
1770 }
1771
1772 factory_channel_index_[logged_channel_index] = factory_channel_index;
1773}
1774
1775bool LogReader::State::Send(
1776 size_t channel_index, const void *data, size_t size,
1777 const TimestampMerger::DeliveryTimestamp &delivery_timestamp) {
1778 aos::RawSender *sender = channels_[channel_index].get();
1779 uint32_t remote_queue_index = 0xffffffff;
1780
1781 if (remote_timestamp_senders_[channel_index] != nullptr) {
1782 std::vector<SentTimestamp> *queue_index_map =
1783 CHECK_NOTNULL(CHECK_NOTNULL(channel_source_state_[channel_index])
1784 ->queue_index_map_[channel_index]
1785 .get());
1786
1787 SentTimestamp search;
1788 search.monotonic_event_time = delivery_timestamp.monotonic_remote_time;
1789 search.realtime_event_time = delivery_timestamp.realtime_remote_time;
1790 search.queue_index = delivery_timestamp.remote_queue_index;
1791
1792 // Find the sent time if available.
1793 auto element = std::lower_bound(
1794 queue_index_map->begin(), queue_index_map->end(), search,
1795 [](SentTimestamp a, SentTimestamp b) {
1796 if (b.monotonic_event_time < a.monotonic_event_time) {
1797 return false;
1798 }
1799 if (b.monotonic_event_time > a.monotonic_event_time) {
1800 return true;
1801 }
1802
1803 if (b.queue_index < a.queue_index) {
1804 return false;
1805 }
1806 if (b.queue_index > a.queue_index) {
1807 return true;
1808 }
1809
1810 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1811 return false;
1812 });
1813
1814 // TODO(austin): Be a bit more principled here, but we will want to do that
1815 // after the logger rewrite. We hit this when one node finishes, but the
1816 // other node isn't done yet. So there is no send time, but there is a
1817 // receive time.
1818 if (element != queue_index_map->end()) {
1819 CHECK_EQ(element->monotonic_event_time,
1820 delivery_timestamp.monotonic_remote_time);
1821 CHECK_EQ(element->realtime_event_time,
1822 delivery_timestamp.realtime_remote_time);
1823 CHECK_EQ(element->queue_index, delivery_timestamp.remote_queue_index);
1824
1825 remote_queue_index = element->actual_queue_index;
1826 }
1827 }
1828
1829 // Send! Use the replayed queue index here instead of the logged queue index
1830 // for the remote queue index. This makes re-logging work.
1831 const bool sent =
1832 sender->Send(data, size, delivery_timestamp.monotonic_remote_time,
1833 delivery_timestamp.realtime_remote_time, remote_queue_index);
1834 if (!sent) return false;
1835
1836 if (queue_index_map_[channel_index]) {
1837 SentTimestamp timestamp;
1838 timestamp.monotonic_event_time = delivery_timestamp.monotonic_event_time;
1839 timestamp.realtime_event_time = delivery_timestamp.realtime_event_time;
1840 timestamp.queue_index = delivery_timestamp.queue_index;
1841 timestamp.actual_queue_index = sender->sent_queue_index();
1842 queue_index_map_[channel_index]->emplace_back(timestamp);
1843 } else if (remote_timestamp_senders_[channel_index] != nullptr) {
1844 aos::Sender<MessageHeader>::Builder builder =
1845 remote_timestamp_senders_[channel_index]->MakeBuilder();
1846
1847 logger::MessageHeader::Builder message_header_builder =
1848 builder.MakeBuilder<logger::MessageHeader>();
1849
1850 message_header_builder.add_channel_index(
1851 factory_channel_index_[channel_index]);
1852
1853 // Swap the remote and sent metrics. They are from the sender's
1854 // perspective, not the receiver's perspective.
1855 message_header_builder.add_monotonic_sent_time(
1856 sender->monotonic_sent_time().time_since_epoch().count());
1857 message_header_builder.add_realtime_sent_time(
1858 sender->realtime_sent_time().time_since_epoch().count());
1859 message_header_builder.add_queue_index(sender->sent_queue_index());
1860
1861 message_header_builder.add_monotonic_remote_time(
1862 delivery_timestamp.monotonic_remote_time.time_since_epoch().count());
1863 message_header_builder.add_realtime_remote_time(
1864 delivery_timestamp.realtime_remote_time.time_since_epoch().count());
1865
1866 message_header_builder.add_remote_queue_index(remote_queue_index);
1867
1868 builder.Send(message_header_builder.Finish());
1869 }
1870
1871 return true;
1872}
1873
1874aos::Sender<MessageHeader> *LogReader::State::RemoteTimestampSender(
1875 const Node *delivered_node) {
1876 auto sender = remote_timestamp_senders_map_.find(delivered_node);
1877
1878 if (sender == remote_timestamp_senders_map_.end()) {
1879 sender = remote_timestamp_senders_map_
1880 .emplace(std::make_pair(
1881 delivered_node,
1882 event_loop()->MakeSender<MessageHeader>(
1883 absl::StrCat("/aos/remote_timestamps/",
1884 delivered_node->name()->string_view()))))
1885 .first;
1886 }
1887
1888 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07001889}
1890
1891std::tuple<TimestampMerger::DeliveryTimestamp, int,
1892 FlatbufferVector<MessageHeader>>
1893LogReader::State::PopOldest(bool *update_time) {
1894 CHECK_GT(sorted_messages_.size(), 0u);
1895
1896 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001897 FlatbufferVector<MessageHeader>,
1898 message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001899 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001900 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001901 << std::get<0>(result).monotonic_event_time;
1902 sorted_messages_.pop_front();
1903 SeedSortedMessages();
1904
Austin Schuh2f8fd752020-09-01 22:38:28 -07001905 if (std::get<3>(result) != nullptr) {
1906 *update_time = std::get<3>(result)->Pop(
1907 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1908 } else {
1909 *update_time = false;
1910 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001911 return std::make_tuple(std::get<0>(result), std::get<1>(result),
1912 std::move(std::get<2>(result)));
1913}
1914
1915monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1916 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001917 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001918 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1919 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1920 }
1921
1922 return channel_merger_->OldestMessageTime();
1923}
1924
1925void LogReader::State::SeedSortedMessages() {
1926 const aos::monotonic_clock::time_point end_queue_time =
1927 (sorted_messages_.size() > 0
1928 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
1929 : channel_merger_->monotonic_start_time()) +
1930 std::chrono::seconds(2);
1931
1932 while (true) {
1933 if (channel_merger_->OldestMessageTime() == monotonic_clock::max_time) {
1934 return;
1935 }
1936 if (sorted_messages_.size() > 0) {
1937 // Stop placing sorted messages on the list once we have 2 seconds
1938 // queued up (but queue at least until the log starts.
1939 if (end_queue_time <
1940 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
1941 return;
1942 }
1943 }
1944
1945 TimestampMerger::DeliveryTimestamp channel_timestamp;
1946 int channel_index;
1947 FlatbufferVector<MessageHeader> channel_data =
1948 FlatbufferVector<MessageHeader>::Empty();
1949
Austin Schuh2f8fd752020-09-01 22:38:28 -07001950 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
1951
Austin Schuh858c9f32020-08-31 16:56:12 -07001952 std::tie(channel_timestamp, channel_index, channel_data) =
1953 channel_merger_->PopOldest();
1954
Austin Schuh2f8fd752020-09-01 22:38:28 -07001955 // Skip any messages without forwarding information.
1956 if (channel_timestamp.monotonic_remote_time != monotonic_clock::min_time) {
1957 // Got a forwarding timestamp!
1958 filter = filters_[channel_index];
1959
1960 CHECK(filter != nullptr);
1961
1962 // Call the correct method depending on if we are the forward or
1963 // reverse direction here.
1964 filter->Sample(event_loop_->node(),
1965 channel_timestamp.monotonic_event_time,
1966 channel_timestamp.monotonic_remote_time);
1967 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001968 sorted_messages_.emplace_back(channel_timestamp, channel_index,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001969 std::move(channel_data), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07001970 }
1971}
1972
1973void LogReader::State::Deregister() {
1974 for (size_t i = 0; i < channels_.size(); ++i) {
1975 channels_[i].reset();
1976 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001977 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001978 event_loop_unique_ptr_.reset();
1979 event_loop_ = nullptr;
1980 timer_handler_ = nullptr;
1981 node_event_loop_factory_ = nullptr;
1982}
1983
Austin Schuhe309d2a2019-11-29 13:25:21 -08001984} // namespace logger
1985} // namespace aos