blob: 7d0040c2faa74a592fbe795aaed6d43408111194 [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 Schuhe309d2a2019-11-29 13:25:21 -080038namespace chrono = std::chrono;
39
Brian Silverman1f345222020-09-24 21:14:48 -070040Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
41 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -080042 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -070043 configuration_(configuration),
Brian Silvermanae7c0332020-09-30 16:58:23 -070044 boot_uuid_(
45 util::ReadFileToStringOrDie("/proc/sys/kernel/random/boot_id")),
Austin Schuh0c297012020-09-16 18:41:59 -070046 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -070047 timer_handler_(event_loop_->AddTimer(
48 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -070049 server_statistics_fetcher_(
50 configuration::MultiNode(event_loop_->configuration())
51 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
52 "/aos")
53 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -070054 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070055
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070056 // Find all the nodes which are logging timestamps on our node. This may
57 // over-estimate if should_log is specified.
58 std::vector<const Node *> timestamp_logger_nodes =
59 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070060
61 std::map<const Channel *, const Node *> timestamp_logger_channels;
62
63 // Now that we have all the nodes accumulated, make remote timestamp loggers
64 // for them.
65 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070066 // Note: since we are doing a find using the event loop channel, we need to
67 // make sure this channel pointer is part of the event loop configuration,
68 // not configuration_. This only matters when configuration_ !=
69 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -070070 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070071 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -070072 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
73 logger::MessageHeader::GetFullyQualifiedName(), event_loop_->name(),
74 event_loop_->node());
75
76 CHECK(channel != nullptr)
77 << ": Remote timestamps are logged on "
78 << event_loop_->node()->name()->string_view()
79 << " but can't find channel /aos/remote_timestamps/"
80 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -070081 if (!should_log(channel)) {
82 continue;
83 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070084 timestamp_logger_channels.insert(std::make_pair(channel, node));
85 }
86
Brian Silvermand90905f2020-09-23 14:42:56 -070087 const size_t our_node_index =
88 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070089
Brian Silverman1f345222020-09-24 21:14:48 -070090 for (size_t channel_index = 0;
91 channel_index < configuration_->channels()->size(); ++channel_index) {
92 const Channel *const config_channel =
93 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -070094 // The MakeRawFetcher method needs a channel which is in the event loop
95 // configuration() object, not the configuration_ object. Go look that up
96 // from the config.
97 const Channel *channel = aos::configuration::GetChannel(
98 event_loop_->configuration(), config_channel->name()->string_view(),
99 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700100 CHECK(channel != nullptr)
101 << ": Failed to look up channel "
102 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700103 if (!should_log(channel)) {
104 continue;
105 }
Austin Schuh0c297012020-09-16 18:41:59 -0700106
Austin Schuhe309d2a2019-11-29 13:25:21 -0800107 FetcherStruct fs;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700108 fs.node_index = our_node_index;
Brian Silverman1f345222020-09-24 21:14:48 -0700109 fs.channel_index = channel_index;
110 fs.channel = channel;
111
Austin Schuh6f3babe2020-01-26 20:34:50 -0800112 const bool is_local =
113 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
114
Austin Schuh15649d62019-12-28 16:36:38 -0800115 const bool is_readable =
116 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700117 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
118 channel, event_loop_->node());
119 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800120
Brian Silverman1f345222020-09-24 21:14:48 -0700121 bool log_delivery_times = false;
122 if (event_loop_->node() != nullptr) {
123 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
124 channel, event_loop_->node(), event_loop_->node());
125 }
Austin Schuh15649d62019-12-28 16:36:38 -0800126
Austin Schuh2f8fd752020-09-01 22:38:28 -0700127 // Now, detect a MessageHeader timestamp logger where we should just log the
128 // contents to a file directly.
129 const bool log_contents = timestamp_logger_channels.find(channel) !=
130 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700131
132 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800133 fs.fetcher = event_loop->MakeRawFetcher(channel);
134 VLOG(1) << "Logging channel "
135 << configuration::CleanedChannelToString(channel);
136
137 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800138 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700139 fs.wants_timestamp_writer = true;
Austin Schuh15649d62019-12-28 16:36:38 -0800140 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800141 if (log_message) {
142 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700143 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800144 if (!is_local) {
145 fs.log_type = LogType::kLogRemoteMessage;
146 }
147 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700148 if (log_contents) {
149 VLOG(1) << "Timestamp logger channel "
150 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700151 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
152 fs.wants_contents_writer = true;
Austin Schuh0c297012020-09-16 18:41:59 -0700153 fs.node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700154 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700155 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800156 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800157 }
Brian Silverman1f345222020-09-24 21:14:48 -0700158 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700159
160 // When we are logging remote timestamps, we need to be able to translate from
161 // the channel index that the event loop uses to the channel index in the
162 // config in the log file.
163 event_loop_to_logged_channel_index_.resize(
164 event_loop->configuration()->channels()->size(), -1);
165 for (size_t event_loop_channel_index = 0;
166 event_loop_channel_index <
167 event_loop->configuration()->channels()->size();
168 ++event_loop_channel_index) {
169 const Channel *event_loop_channel =
170 event_loop->configuration()->channels()->Get(event_loop_channel_index);
171
172 const Channel *logged_channel = aos::configuration::GetChannel(
173 configuration_, event_loop_channel->name()->string_view(),
174 event_loop_channel->type()->string_view(), "",
175 configuration::GetNode(configuration_, event_loop_->node()));
176
177 if (logged_channel != nullptr) {
178 event_loop_to_logged_channel_index_[event_loop_channel_index] =
179 configuration::ChannelIndex(configuration_, logged_channel);
180 }
181 }
Brian Silverman1f345222020-09-24 21:14:48 -0700182}
183
184Logger::~Logger() {
185 if (log_namer_) {
186 // If we are replaying a log file, or in simulation, we want to force the
187 // last bit of data to be logged. The easiest way to deal with this is to
188 // poll everything as we go to destroy the class, ie, shut down the logger,
189 // and write it to disk.
190 StopLogging(event_loop_->monotonic_now());
191 }
192}
193
Brian Silvermanae7c0332020-09-30 16:58:23 -0700194void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
195 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700196 CHECK(!log_namer_) << ": Already logging";
197 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700198 log_event_uuid_ = UUID::Random();
199 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700200 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
201
202 // We want to do as much work as possible before the initial Fetch. Time
203 // between that and actually starting to log opens up the possibility of
204 // falling off the end of the queue during that time.
205
206 for (FetcherStruct &f : fetchers_) {
207 if (f.wants_writer) {
208 f.writer = log_namer_->MakeWriter(f.channel);
209 }
210 if (f.wants_timestamp_writer) {
211 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
212 }
213 if (f.wants_contents_writer) {
214 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
215 f.channel, CHECK_NOTNULL(f.timestamp_node));
216 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800217 }
218
Brian Silverman1f345222020-09-24 21:14:48 -0700219 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700220 node_state_.resize(configuration::MultiNode(configuration_)
221 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700222 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800223
Austin Schuh2f8fd752020-09-01 22:38:28 -0700224 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700225 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800226
Austin Schuh2f8fd752020-09-01 22:38:28 -0700227 node_state_[node_index].log_file_header = MakeHeader(node);
228 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800229
Austin Schuh2f8fd752020-09-01 22:38:28 -0700230 // Grab data from each channel right before we declare the log file started
231 // so we can capture the latest message on each channel. This lets us have
232 // non periodic messages with configuration that now get logged.
233 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700234 const auto start = event_loop_->monotonic_now();
235 const bool got_new = f.fetcher->Fetch();
236 const auto end = event_loop_->monotonic_now();
237 RecordFetchResult(start, end, got_new, &f);
238
239 // If there is a message, we want to write it.
240 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700241 }
242
243 // Clear out any old timestamps in case we are re-starting logging.
244 for (size_t i = 0; i < node_state_.size(); ++i) {
245 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time);
246 }
247
248 WriteHeader();
249
250 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
251 << " start_time " << last_synchronized_time_;
252
253 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
254 polling_period_);
255}
256
Brian Silverman1f345222020-09-24 21:14:48 -0700257std::unique_ptr<LogNamer> Logger::StopLogging(
258 aos::monotonic_clock::time_point end_time) {
259 CHECK(log_namer_) << ": Not logging right now";
260
261 if (end_time != aos::monotonic_clock::min_time) {
262 LogUntil(end_time);
263 }
264 timer_handler_->Disable();
265
266 for (FetcherStruct &f : fetchers_) {
267 f.writer = nullptr;
268 f.timestamp_writer = nullptr;
269 f.contents_writer = nullptr;
270 }
271 node_state_.clear();
272
Brian Silvermanae7c0332020-09-30 16:58:23 -0700273 log_event_uuid_ = UUID::Zero();
274 log_start_uuid_ = std::string();
275
Brian Silverman1f345222020-09-24 21:14:48 -0700276 return std::move(log_namer_);
277}
278
Austin Schuhfa895892020-01-07 20:07:41 -0800279void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700280 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700281 server_statistics_fetcher_.Fetch();
282 }
283
284 aos::monotonic_clock::time_point monotonic_start_time =
285 event_loop_->monotonic_now();
286 aos::realtime_clock::time_point realtime_start_time =
287 event_loop_->realtime_now();
288
289 // We need to pick a point in time to declare the log file "started". This
290 // starts here. It needs to be after everything is fetched so that the
291 // fetchers are all pointed at the most recent message before the start
292 // time.
293 last_synchronized_time_ = monotonic_start_time;
294
Austin Schuh6f3babe2020-01-26 20:34:50 -0800295 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700296 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700297 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
298 realtime_start_time);
Austin Schuh64fab802020-09-09 22:47:47 -0700299 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800300 }
301}
Austin Schuh8bd96322020-02-13 21:18:22 -0800302
Austin Schuh2f8fd752020-09-01 22:38:28 -0700303void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700304 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700305 server_statistics_fetcher_.Fetch();
306 } else {
307 return;
308 }
309
310 if (server_statistics_fetcher_.get() == nullptr) {
311 return;
312 }
313
314 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700315 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700316 if (MaybeUpdateTimestamp(
317 node, node_index,
318 server_statistics_fetcher_.context().monotonic_event_time,
319 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh64fab802020-09-09 22:47:47 -0700320 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700321 }
322 }
323}
324
325void Logger::SetStartTime(size_t node_index,
326 aos::monotonic_clock::time_point monotonic_start_time,
327 aos::realtime_clock::time_point realtime_start_time) {
328 node_state_[node_index].monotonic_start_time = monotonic_start_time;
329 node_state_[node_index].realtime_start_time = realtime_start_time;
330 node_state_[node_index]
331 .log_file_header.mutable_message()
332 ->mutate_monotonic_start_time(
333 std::chrono::duration_cast<std::chrono::nanoseconds>(
334 monotonic_start_time.time_since_epoch())
335 .count());
336 if (node_state_[node_index]
337 .log_file_header.mutable_message()
338 ->has_realtime_start_time()) {
339 node_state_[node_index]
340 .log_file_header.mutable_message()
341 ->mutate_realtime_start_time(
342 std::chrono::duration_cast<std::chrono::nanoseconds>(
343 realtime_start_time.time_since_epoch())
344 .count());
345 }
346}
347
348bool Logger::MaybeUpdateTimestamp(
349 const Node *node, int node_index,
350 aos::monotonic_clock::time_point monotonic_start_time,
351 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700352 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700353 if (node_state_[node_index].monotonic_start_time !=
354 monotonic_clock::min_time) {
355 return false;
356 }
Austin Schuh0c297012020-09-16 18:41:59 -0700357 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700358 if (event_loop_->node() == node) {
359 // There are no offsets to compute for ourself, so always succeed.
360 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
361 return true;
362 } else if (server_statistics_fetcher_.get() != nullptr) {
363 // We must be a remote node now. Look for the connection and see if it is
364 // connected.
365
366 for (const message_bridge::ServerConnection *connection :
367 *server_statistics_fetcher_->connections()) {
368 if (connection->node()->name()->string_view() !=
369 node->name()->string_view()) {
370 continue;
371 }
372
373 if (connection->state() != message_bridge::State::CONNECTED) {
374 VLOG(1) << node->name()->string_view()
375 << " is not connected, can't start it yet.";
376 break;
377 }
378
379 if (!connection->has_monotonic_offset()) {
380 VLOG(1) << "Missing monotonic offset for setting start time for node "
381 << aos::FlatbufferToJson(node);
382 break;
383 }
384
385 VLOG(1) << "Updating start time for " << aos::FlatbufferToJson(node);
386
387 // Found it and it is connected. Compensate and go.
388 monotonic_start_time +=
389 std::chrono::nanoseconds(connection->monotonic_offset());
390
391 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
392 return true;
393 }
394 }
395 } else {
396 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
397 return true;
398 }
399 return false;
400}
401
402aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
403 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800404 // Now write the header with this timestamp in it.
405 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800406 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800407
Austin Schuh2f8fd752020-09-01 22:38:28 -0700408 // TODO(austin): Compress this much more efficiently. There are a bunch of
409 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700410 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700411 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800412
Brian Silvermanae7c0332020-09-30 16:58:23 -0700413 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700414 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800415
Brian Silvermanae7c0332020-09-30 16:58:23 -0700416 CHECK(log_event_uuid_ != UUID::Zero());
417 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
418 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700419
Brian Silvermanae7c0332020-09-30 16:58:23 -0700420 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
421 fbb.CreateString(logger_instance_uuid_.string_view());
422
423 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
424 if (!log_start_uuid_.empty()) {
425 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
426 }
427
428 const flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
429 fbb.CreateString(boot_uuid_);
430
431 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700432 fbb.CreateString("00000000-0000-4000-8000-000000000000");
433
Austin Schuhfa895892020-01-07 20:07:41 -0800434 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700435 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700436
Austin Schuh0c297012020-09-16 18:41:59 -0700437 if (configuration::MultiNode(configuration_)) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800438 node_offset = CopyFlatBuffer(node, &fbb);
Brian Silverman80993c22020-10-01 15:05:19 -0700439 logger_node_offset = CopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800440 }
441
442 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
443
Austin Schuh64fab802020-09-09 22:47:47 -0700444 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800445
446 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800447 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800448 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700449 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800450 }
451
452 log_file_header_builder.add_configuration(configuration_offset);
453 // The worst case theoretical out of order is the polling period times 2.
454 // One message could get logged right after the boundary, but be for right
455 // before the next boundary. And the reverse could happen for another
456 // message. Report back 3x to be extra safe, and because the cost isn't
457 // huge on the read side.
458 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700459 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800460
461 log_file_header_builder.add_monotonic_start_time(
462 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800464 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700465 if (node == event_loop_->node()) {
466 log_file_header_builder.add_realtime_start_time(
467 std::chrono::duration_cast<std::chrono::nanoseconds>(
468 realtime_clock::min_time.time_since_epoch())
469 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800470 }
471
Brian Silvermanae7c0332020-09-30 16:58:23 -0700472 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
473 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
474 if (!log_start_uuid_offset.IsNull()) {
475 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
476 }
477 log_file_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700478
479 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
480 log_file_header_builder.add_parts_index(0);
481
Austin Schuh2f8fd752020-09-01 22:38:28 -0700482 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
483 return fbb.Release();
484}
485
Brian Silvermancb805822020-10-06 17:43:35 -0700486void Logger::ResetStatisics() {
487 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
488 max_message_fetch_time_channel_ = -1;
489 max_message_fetch_time_size_ = -1;
490 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
491 total_message_fetch_count_ = 0;
492 total_message_fetch_bytes_ = 0;
493 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
494 total_nop_fetch_count_ = 0;
495 max_copy_time_ = std::chrono::nanoseconds::zero();
496 max_copy_time_channel_ = -1;
497 max_copy_time_size_ = -1;
498 total_copy_time_ = std::chrono::nanoseconds::zero();
499 total_copy_count_ = 0;
500 total_copy_bytes_ = 0;
501}
502
Austin Schuh2f8fd752020-09-01 22:38:28 -0700503void Logger::Rotate() {
504 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700505 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700506 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700507 }
508}
509
510void Logger::LogUntil(monotonic_clock::time_point t) {
511 WriteMissingTimestamps();
512
513 // Write each channel to disk, one at a time.
514 for (FetcherStruct &f : fetchers_) {
515 while (true) {
516 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700517 const auto start = event_loop_->monotonic_now();
518 const bool got_new = f.fetcher->FetchNext();
519 const auto end = event_loop_->monotonic_now();
520 RecordFetchResult(start, end, got_new, &f);
521 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700522 VLOG(2) << "No new data on "
523 << configuration::CleanedChannelToString(
524 f.fetcher->channel());
525 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700526 }
Brian Silvermancb805822020-10-06 17:43:35 -0700527 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700528 }
529
Austin Schuh2f8fd752020-09-01 22:38:28 -0700530 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700531 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700532 break;
533 }
Brian Silvermancb805822020-10-06 17:43:35 -0700534 if (f.writer != nullptr) {
535 // Write!
536 const auto start = event_loop_->monotonic_now();
537 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
538 max_header_size_);
539 fbb.ForceDefaults(true);
540
541 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
542 f.channel_index, f.log_type));
543 const auto end = event_loop_->monotonic_now();
544 RecordCreateMessageTime(start, end, &f);
545
546 VLOG(2) << "Writing data as node "
547 << FlatbufferToJson(event_loop_->node()) << " for channel "
548 << configuration::CleanedChannelToString(f.fetcher->channel())
549 << " to " << f.writer->filename() << " data "
550 << FlatbufferToJson(
551 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
552 fbb.GetBufferPointer()));
553
554 max_header_size_ = std::max(max_header_size_,
555 fbb.GetSize() - f.fetcher->context().size);
556 f.writer->QueueSizedFlatbuffer(&fbb);
557 }
558
559 if (f.timestamp_writer != nullptr) {
560 // And now handle timestamps.
561 const auto start = event_loop_->monotonic_now();
562 flatbuffers::FlatBufferBuilder fbb;
563 fbb.ForceDefaults(true);
564
565 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
566 f.channel_index,
567 LogType::kLogDeliveryTimeOnly));
568 const auto end = event_loop_->monotonic_now();
569 RecordCreateMessageTime(start, end, &f);
570
571 VLOG(2) << "Writing timestamps as node "
572 << FlatbufferToJson(event_loop_->node()) << " for channel "
573 << configuration::CleanedChannelToString(f.fetcher->channel())
574 << " to " << f.timestamp_writer->filename() << " timestamp "
575 << FlatbufferToJson(
576 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
577 fbb.GetBufferPointer()));
578
579 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
580 }
581
582 if (f.contents_writer != nullptr) {
583 const auto start = event_loop_->monotonic_now();
584 // And now handle the special message contents channel. Copy the
585 // message into a FlatBufferBuilder and save it to disk.
586 // TODO(austin): We can be more efficient here when we start to
587 // care...
588 flatbuffers::FlatBufferBuilder fbb;
589 fbb.ForceDefaults(true);
590
591 const MessageHeader *msg =
592 flatbuffers::GetRoot<MessageHeader>(f.fetcher->context().data);
593
594 logger::MessageHeader::Builder message_header_builder(fbb);
595
596 // TODO(austin): This needs to check the channel_index and confirm
597 // that it should be logged before squirreling away the timestamp to
598 // disk. We don't want to log irrelevant timestamps.
599
600 // Note: this must match the same order as MessageBridgeServer and
601 // PackMessage. We want identical headers to have identical
602 // on-the-wire formats to make comparing them easier.
603
604 // Translate from the channel index that the event loop uses to the
605 // channel index in the log file.
606 message_header_builder.add_channel_index(
607 event_loop_to_logged_channel_index_[msg->channel_index()]);
608
609 message_header_builder.add_queue_index(msg->queue_index());
610 message_header_builder.add_monotonic_sent_time(
611 msg->monotonic_sent_time());
612 message_header_builder.add_realtime_sent_time(
613 msg->realtime_sent_time());
614
615 message_header_builder.add_monotonic_remote_time(
616 msg->monotonic_remote_time());
617 message_header_builder.add_realtime_remote_time(
618 msg->realtime_remote_time());
619 message_header_builder.add_remote_queue_index(
620 msg->remote_queue_index());
621
622 fbb.FinishSizePrefixed(message_header_builder.Finish());
623 const auto end = event_loop_->monotonic_now();
624 RecordCreateMessageTime(start, end, &f);
625
626 f.contents_writer->QueueSizedFlatbuffer(&fbb);
627 }
628
629 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700630 }
631 }
632 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800633}
634
Brian Silverman1f345222020-09-24 21:14:48 -0700635void Logger::DoLogData(const monotonic_clock::time_point end_time) {
636 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800637 // max_out_of_order_duration. To do this, we need sync points. Every write
638 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800639
640 do {
641 // Move the sync point up by at most polling_period. This forces one sync
642 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700643 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
644
645 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800646
Austin Schuhe309d2a2019-11-29 13:25:21 -0800647 // If we missed cycles, we could be pretty far behind. Spin until we are
648 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700649 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800650}
651
Brian Silvermancb805822020-10-06 17:43:35 -0700652void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
653 aos::monotonic_clock::time_point end,
654 bool got_new, FetcherStruct *fetcher) {
655 const auto duration = end - start;
656 if (!got_new) {
657 ++total_nop_fetch_count_;
658 total_nop_fetch_time_ += duration;
659 return;
660 }
661 ++total_message_fetch_count_;
662 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
663 total_message_fetch_time_ += duration;
664 if (duration > max_message_fetch_time_) {
665 max_message_fetch_time_ = duration;
666 max_message_fetch_time_channel_ = fetcher->channel_index;
667 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
668 }
669}
670
671void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
672 aos::monotonic_clock::time_point end,
673 FetcherStruct *fetcher) {
674 const auto duration = end - start;
675 total_copy_time_ += duration;
676 ++total_copy_count_;
677 total_copy_bytes_ += fetcher->fetcher->context().size;
678 if (duration > max_copy_time_) {
679 max_copy_time_ = duration;
680 max_copy_time_channel_ = fetcher->channel_index;
681 max_copy_time_size_ = fetcher->fetcher->context().size;
682 }
683}
684
Austin Schuh11d43732020-09-21 17:28:30 -0700685std::vector<std::vector<std::string>> ToLogReaderVector(
686 const std::vector<LogFile> &log_files) {
687 std::vector<std::vector<std::string>> result;
688 for (const LogFile &log_file : log_files) {
689 for (const LogParts &log_parts : log_file.parts) {
690 std::vector<std::string> parts;
691 for (const std::string &part : log_parts.parts) {
692 parts.emplace_back(part);
693 }
694 result.emplace_back(std::move(parts));
695 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700696 }
697 return result;
698}
699
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800700LogReader::LogReader(std::string_view filename,
701 const Configuration *replay_configuration)
Austin Schuhfa895892020-01-07 20:07:41 -0800702 : LogReader(std::vector<std::string>{std::string(filename)},
703 replay_configuration) {}
704
705LogReader::LogReader(const std::vector<std::string> &filenames,
706 const Configuration *replay_configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800707 : LogReader(std::vector<std::vector<std::string>>{filenames},
708 replay_configuration) {}
709
Austin Schuh11d43732020-09-21 17:28:30 -0700710// TODO(austin): Make this the base and kill the others. This has much better
711// context for sorting.
712LogReader::LogReader(const std::vector<LogFile> &log_files,
713 const Configuration *replay_configuration)
714 : LogReader(ToLogReaderVector(log_files), replay_configuration) {}
715
Austin Schuh6f3babe2020-01-26 20:34:50 -0800716LogReader::LogReader(const std::vector<std::vector<std::string>> &filenames,
717 const Configuration *replay_configuration)
718 : filenames_(filenames),
719 log_file_header_(ReadHeader(filenames[0][0])),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800720 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800721 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800722
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700723 // Remap all existing remote timestamp channels. They will be recreated, and
724 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700725 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700726 std::vector<const Node *> timestamp_logger_nodes =
727 configuration::TimestampNodes(logged_configuration(), node);
728 for (const Node *remote_node : timestamp_logger_nodes) {
729 const std::string channel = absl::StrCat(
730 "/aos/remote_timestamps/", remote_node->name()->string_view());
731 CHECK(HasChannel<logger::MessageHeader>(channel, node))
732 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
733 << logger::MessageHeader::GetFullyQualifiedName() << "\"} for node "
734 << node->name()->string_view();
735 RemapLoggedChannel<logger::MessageHeader>(channel, node);
736 }
737 }
738
Austin Schuh6aa77be2020-02-22 21:06:40 -0800739 if (replay_configuration) {
740 CHECK_EQ(configuration::MultiNode(configuration()),
741 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700742 << ": Log file and replay config need to both be multi or single "
743 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800744 }
745
Austin Schuh6f3babe2020-01-26 20:34:50 -0800746 if (!configuration::MultiNode(configuration())) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700747 states_.emplace_back(
748 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800749 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800750 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700751 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800752 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700753 << ": Log file and replay config need to have matching nodes "
754 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700755 for (const Node *node : *logged_configuration()->nodes()) {
756 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700757 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
758 << " in logged config that is not present in the replay "
759 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700760 }
761 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800762 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800763 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800764 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800765}
766
Austin Schuh6aa77be2020-02-22 21:06:40 -0800767LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700768 if (event_loop_factory_unique_ptr_) {
769 Deregister();
770 } else if (event_loop_factory_ != nullptr) {
771 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
772 "is destroyed";
773 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800774 if (offset_fp_ != nullptr) {
775 fclose(offset_fp_);
776 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700777 // Zero out some buffers. It's easy to do use-after-frees on these, so make
778 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700779 if (remapped_configuration_buffer_) {
780 remapped_configuration_buffer_->Wipe();
781 }
782 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -0800783}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800784
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800785const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800786 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800787}
788
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800789const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800790 return remapped_configuration_;
791}
792
Austin Schuh6f3babe2020-01-26 20:34:50 -0800793std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700794 // Because the Node pointer will only be valid if it actually points to
795 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800796 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800797 //
798 // Also, note, that when ever a map is changed, the nodes in here are
799 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800800 CHECK(remapped_configuration_ != nullptr)
801 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800802 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800803}
Austin Schuh15649d62019-12-28 16:36:38 -0800804
Austin Schuh11d43732020-09-21 17:28:30 -0700805monotonic_clock::time_point LogReader::monotonic_start_time(
806 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800807 State *state =
808 states_[configuration::GetNodeIndex(configuration(), node)].get();
809 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
810
Austin Schuh858c9f32020-08-31 16:56:12 -0700811 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800812}
813
Austin Schuh11d43732020-09-21 17:28:30 -0700814realtime_clock::time_point LogReader::realtime_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->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800821}
822
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800823void LogReader::Register() {
824 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800825 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800826 Register(event_loop_factory_unique_ptr_.get());
827}
828
Austin Schuh92547522019-12-28 14:33:43 -0800829void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800830 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700831 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -0800832
Brian Silvermand90905f2020-09-23 14:42:56 -0700833 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800834 const size_t node_index =
835 configuration::GetNodeIndex(configuration(), node);
Austin Schuh858c9f32020-08-31 16:56:12 -0700836 states_[node_index] =
837 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames_));
Austin Schuh8bd96322020-02-13 21:18:22 -0800838 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700839 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700840 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700841
842 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -0800843 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700844
845 // Register after making all the State objects so we can build references
846 // between them.
847 for (const Node *node : configuration::GetNodes(configuration())) {
848 const size_t node_index =
849 configuration::GetNodeIndex(configuration(), node);
850 State *state = states_[node_index].get();
851
852 Register(state->event_loop());
853 }
854
James Kuszmaul46d82582020-05-09 19:50:09 -0700855 if (live_nodes_ == 0) {
856 LOG(FATAL)
857 << "Don't have logs from any of the nodes in the replay config--are "
858 "you sure that the replay config matches the original config?";
859 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800860
Austin Schuh2f8fd752020-09-01 22:38:28 -0700861 // We need to now seed our per-node time offsets and get everything set up
862 // to run.
863 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -0800864
Austin Schuh8bd96322020-02-13 21:18:22 -0800865 // It is easiest to solve for per node offsets with a matrix rather than
866 // trying to solve the equations by hand. So let's get after it.
867 //
868 // Now, build up the map matrix.
869 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700870 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
871 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
872 filters_.size() + 1, num_nodes);
873 slope_matrix_ =
874 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
875 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800876
Austin Schuh2f8fd752020-09-01 22:38:28 -0700877 offset_matrix_ =
878 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
879 valid_matrix_ =
880 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
881 last_valid_matrix_ =
882 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -0800883
Austin Schuh2f8fd752020-09-01 22:38:28 -0700884 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
885 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -0800886
Austin Schuh2f8fd752020-09-01 22:38:28 -0700887 // All times should average out to the distributed clock.
888 for (int i = 0; i < map_matrix_.cols(); ++i) {
889 // 1/num_nodes.
890 map_matrix_(0, i) = mpq_class(1, num_nodes);
891 }
892 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800893
894 {
895 // Now, add the a - b -> sample elements.
896 size_t i = 1;
897 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -0700898 std::tuple<message_bridge::NoncausalOffsetEstimator>>
899 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800900 const Node *const node_a = std::get<0>(filter.first);
901 const Node *const node_b = std::get<1>(filter.first);
902
903 const size_t node_a_index =
904 configuration::GetNodeIndex(configuration(), node_a);
905 const size_t node_b_index =
906 configuration::GetNodeIndex(configuration(), node_b);
907
Austin Schuh2f8fd752020-09-01 22:38:28 -0700908 // -a
909 map_matrix_(i, node_a_index) = mpq_class(-1);
910 // +b
911 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -0800912
913 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -0700914 std::get<0>(filter.second)
915 .set_slope_pointer(&slope_matrix_(i, node_a_index));
916 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
917
918 valid_matrix_(i) = false;
919 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -0800920
921 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800922 }
923 }
924
Austin Schuh858c9f32020-08-31 16:56:12 -0700925 for (std::unique_ptr<State> &state : states_) {
926 state->SeedSortedMessages();
927 }
928
Austin Schuh2f8fd752020-09-01 22:38:28 -0700929 // Rank of the map matrix tells you if all the nodes are in communication
930 // with each other, which tells you if the offsets are observable.
931 const size_t connected_nodes =
932 Eigen::FullPivLU<
933 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
934 .rank();
935
936 // We don't need to support isolated nodes until someone has a real use
937 // case.
938 CHECK_EQ(connected_nodes, num_nodes)
939 << ": There is a node which isn't communicating with the rest.";
940
941 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -0800942 UpdateOffsets();
943
Austin Schuh2f8fd752020-09-01 22:38:28 -0700944 // We want to start the log file at the last start time of the log files
945 // from all the nodes. Compute how long each node's simulation needs to run
946 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800947 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800948
Austin Schuh2f8fd752020-09-01 22:38:28 -0700949 // TODO(austin): We want an "OnStart" callback for each node rather than
950 // running until the last node.
951
Austin Schuh8bd96322020-02-13 21:18:22 -0800952 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700953 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
954 << MaybeNodeName(state->event_loop()->node()) << "now "
955 << state->monotonic_now();
956 // And start computing the start time on the distributed clock now that
957 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -0700958 start_time = std::max(
959 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -0800960 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700961
962 CHECK_GE(start_time, distributed_clock::epoch())
963 << ": Hmm, we have a node starting before the start of time. Offset "
964 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -0800965
Austin Schuh6f3babe2020-01-26 20:34:50 -0800966 // Forwarding is tracked per channel. If it is enabled, we want to turn it
967 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -0700968 // nodes, and also replayed on the other nodes. This may not satisfy all
969 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800970 if (configuration::MultiNode(event_loop_factory_->configuration())) {
971 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
972 const Channel *channel = logged_configuration()->channels()->Get(i);
973 const Node *node = configuration::GetNode(
974 configuration(), channel->source_node()->string_view());
975
Austin Schuh8bd96322020-02-13 21:18:22 -0800976 State *state =
977 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800978
979 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -0700980 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800981
982 event_loop_factory_->DisableForwarding(remapped_channel);
983 }
Austin Schuh4c3b9702020-08-30 11:34:55 -0700984
985 // If we are replaying a log, we don't want a bunch of redundant messages
986 // from both the real message bridge and simulated message bridge.
987 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800988 }
989
Austin Schuhcde938c2020-02-02 17:30:07 -0800990 // While we are starting the system up, we might be relying on matching data
991 // to timestamps on log files where the timestamp log file starts before the
992 // data. In this case, it is reasonable to expect missing data.
993 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700994 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -0800995 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -0700996 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -0800997 // Now that we are running for real, missing data means that the log file is
998 // corrupted or went wrong.
999 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001000
Austin Schuh8bd96322020-02-13 21:18:22 -08001001 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001002 // Make the RT clock be correct before handing it to the user.
1003 if (state->realtime_start_time() != realtime_clock::min_time) {
1004 state->SetRealtimeOffset(state->monotonic_start_time(),
1005 state->realtime_start_time());
1006 }
1007 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1008 << MaybeNodeName(state->event_loop()->node()) << "now "
1009 << state->monotonic_now();
1010 }
1011
1012 if (FLAGS_timestamps_to_csv) {
1013 for (std::pair<const std::tuple<const Node *, const Node *>,
1014 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1015 &filter : filters_) {
1016 const Node *const node_a = std::get<0>(filter.first);
1017 const Node *const node_b = std::get<1>(filter.first);
1018
1019 std::get<0>(filter.second)
1020 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1021 ->monotonic_now());
1022 std::get<0>(filter.second)
1023 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1024 ->monotonic_now());
1025 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001026 }
1027}
1028
Austin Schuh2f8fd752020-09-01 22:38:28 -07001029void LogReader::UpdateOffsets() {
1030 VLOG(2) << "Samples are " << offset_matrix_;
1031 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1032 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1033 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1034 "]");
1035 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1036 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1037
1038 size_t node_index = 0;
1039 for (std::unique_ptr<State> &state : states_) {
1040 state->SetDistributedOffset(offset(node_index), slope(node_index));
1041 VLOG(1) << "Offset for node " << node_index << " "
1042 << MaybeNodeName(state->event_loop()->node()) << "is "
1043 << aos::distributed_clock::time_point(offset(node_index))
1044 << " slope " << std::setprecision(9) << std::fixed
1045 << slope(node_index);
1046 ++node_index;
1047 }
1048
1049 if (VLOG_IS_ON(1)) {
1050 LogFit("Offset is");
1051 }
1052}
1053
1054void LogReader::LogFit(std::string_view prefix) {
1055 for (std::unique_ptr<State> &state : states_) {
1056 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1057 << state->monotonic_now() << " distributed "
1058 << event_loop_factory_->distributed_now();
1059 }
1060
1061 for (std::pair<const std::tuple<const Node *, const Node *>,
1062 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1063 filters_) {
1064 message_bridge::NoncausalOffsetEstimator *estimator =
1065 &std::get<0>(filter.second);
1066
1067 if (estimator->a_timestamps().size() == 0 &&
1068 estimator->b_timestamps().size() == 0) {
1069 continue;
1070 }
1071
1072 if (VLOG_IS_ON(1)) {
1073 estimator->LogFit(prefix);
1074 }
1075
1076 const Node *const node_a = std::get<0>(filter.first);
1077 const Node *const node_b = std::get<1>(filter.first);
1078
1079 const size_t node_a_index =
1080 configuration::GetNodeIndex(configuration(), node_a);
1081 const size_t node_b_index =
1082 configuration::GetNodeIndex(configuration(), node_b);
1083
1084 const double recovered_slope =
1085 slope(node_b_index) / slope(node_a_index) - 1.0;
1086 const int64_t recovered_offset =
1087 offset(node_b_index).count() - offset(node_a_index).count() *
1088 slope(node_b_index) /
1089 slope(node_a_index);
1090
1091 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1092 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1093 << " offset " << std::setprecision(20) << recovered_offset
1094 << " (error "
1095 << recovered_offset - estimator->fit().offset().count() << ")";
1096
1097 const aos::distributed_clock::time_point a0 =
1098 states_[node_a_index]->ToDistributedClock(
1099 std::get<0>(estimator->a_timestamps()[0]));
1100 const aos::distributed_clock::time_point a1 =
1101 states_[node_a_index]->ToDistributedClock(
1102 std::get<0>(estimator->a_timestamps()[1]));
1103
1104 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1105 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1106 << " distributed -> " << node_b->name()->string_view() << " "
1107 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1108 << aos::monotonic_clock::time_point(
1109 std::chrono::nanoseconds(static_cast<int64_t>(
1110 std::get<0>(estimator->a_timestamps()[0])
1111 .time_since_epoch()
1112 .count() *
1113 (1.0 + estimator->fit().slope()))) +
1114 estimator->fit().offset())
1115 << ((a0 <= event_loop_factory_->distributed_now())
1116 ? ""
1117 : " After now, investigate");
1118 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1119 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1120 << " distributed -> " << node_b->name()->string_view() << " "
1121 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1122 << aos::monotonic_clock::time_point(
1123 std::chrono::nanoseconds(static_cast<int64_t>(
1124 std::get<0>(estimator->a_timestamps()[1])
1125 .time_since_epoch()
1126 .count() *
1127 (1.0 + estimator->fit().slope()))) +
1128 estimator->fit().offset())
1129 << ((event_loop_factory_->distributed_now() <= a1)
1130 ? ""
1131 : " Before now, investigate");
1132
1133 const aos::distributed_clock::time_point b0 =
1134 states_[node_b_index]->ToDistributedClock(
1135 std::get<0>(estimator->b_timestamps()[0]));
1136 const aos::distributed_clock::time_point b1 =
1137 states_[node_b_index]->ToDistributedClock(
1138 std::get<0>(estimator->b_timestamps()[1]));
1139
1140 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1141 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1142 << " distributed -> " << node_a->name()->string_view() << " "
1143 << states_[node_a_index]->FromDistributedClock(b0)
1144 << ((b0 <= event_loop_factory_->distributed_now())
1145 ? ""
1146 : " After now, investigate");
1147 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1148 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1149 << " distributed -> " << node_a->name()->string_view() << " "
1150 << states_[node_a_index]->FromDistributedClock(b1)
1151 << ((event_loop_factory_->distributed_now() <= b1)
1152 ? ""
1153 : " Before now, investigate");
1154 }
1155}
1156
1157message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001158 const Node *node_a, const Node *node_b) {
1159 CHECK_NE(node_a, node_b);
1160 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1161 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1162
1163 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001164 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001165 }
1166
1167 auto tuple = std::make_tuple(node_a, node_b);
1168
1169 auto it = filters_.find(tuple);
1170
1171 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001172 auto &x =
1173 filters_
1174 .insert(std::make_pair(
1175 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1176 node_a, node_b))))
1177 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001178 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001179 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1180 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1181 node_b->name()->string_view()));
1182 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1183 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1184 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001185 }
1186
Austin Schuh2f8fd752020-09-01 22:38:28 -07001187 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001188 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001189 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001190 }
1191}
1192
Austin Schuhe309d2a2019-11-29 13:25:21 -08001193void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001194 State *state =
1195 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1196 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001197
Austin Schuh858c9f32020-08-31 16:56:12 -07001198 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001199
Tyler Chatow67ddb032020-01-12 14:30:04 -08001200 // We don't run timing reports when trying to print out logged data, because
1201 // otherwise we would end up printing out the timing reports themselves...
1202 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001203 event_loop->SkipTimingReport();
1204 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001205
Austin Schuh858c9f32020-08-31 16:56:12 -07001206 const bool has_data = state->SetNode();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001207
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001208 for (size_t logged_channel_index = 0;
1209 logged_channel_index < logged_configuration()->channels()->size();
1210 ++logged_channel_index) {
1211 const Channel *channel = RemapChannel(
1212 event_loop,
1213 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001214
Austin Schuh2f8fd752020-09-01 22:38:28 -07001215 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001216 aos::Sender<MessageHeader> *remote_timestamp_sender = nullptr;
1217
1218 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001219
1220 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1221 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001222 // We've got a message which is being forwarded to this node.
1223 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001224 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001225 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001226
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001227 // Delivery timestamps are supposed to be logged back on the source node.
1228 // Configure remote timestamps to be sent.
1229 const bool delivery_time_is_logged =
1230 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1231 channel, event_loop->node(), source_node);
1232
1233 source_state =
1234 states_[configuration::GetNodeIndex(configuration(), source_node)]
1235 .get();
1236
1237 if (delivery_time_is_logged) {
1238 remote_timestamp_sender =
1239 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001240 }
1241 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001242
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001243 state->SetChannel(
1244 logged_channel_index,
1245 configuration::ChannelIndex(event_loop->configuration(), channel),
1246 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1247 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001248 }
1249
Austin Schuh6aa77be2020-02-22 21:06:40 -08001250 // If we didn't find any log files with data in them, we won't ever get a
1251 // callback or be live. So skip the rest of the setup.
1252 if (!has_data) {
1253 return;
1254 }
1255
Austin Schuh858c9f32020-08-31 16:56:12 -07001256 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001257 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1258 << "at " << state->event_loop()->context().monotonic_event_time
1259 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001260 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001261 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001262 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001263 if (live_nodes_ == 0) {
1264 event_loop_factory_->Exit();
1265 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001266 return;
1267 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001268 TimestampMerger::DeliveryTimestamp channel_timestamp;
Austin Schuh05b70472020-01-01 17:11:17 -08001269 int channel_index;
1270 FlatbufferVector<MessageHeader> channel_data =
1271 FlatbufferVector<MessageHeader>::Empty();
1272
Austin Schuh2f8fd752020-09-01 22:38:28 -07001273 if (VLOG_IS_ON(1)) {
1274 LogFit("Offset was");
1275 }
1276
1277 bool update_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001278 std::tie(channel_timestamp, channel_index, channel_data) =
Austin Schuh2f8fd752020-09-01 22:38:28 -07001279 state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001280
Austin Schuhe309d2a2019-11-29 13:25:21 -08001281 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001282 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001283 if (!FLAGS_skip_order_validation) {
1284 CHECK(monotonic_now == channel_timestamp.monotonic_event_time)
1285 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1286 << monotonic_now << " trying to send "
1287 << channel_timestamp.monotonic_event_time << " failure "
1288 << state->DebugString();
1289 } else if (monotonic_now != channel_timestamp.monotonic_event_time) {
1290 LOG(WARNING) << "Check failed: monotonic_now == "
1291 "channel_timestamp.monotonic_event_time) ("
1292 << monotonic_now << " vs. "
1293 << channel_timestamp.monotonic_event_time
1294 << "): " << FlatbufferToJson(state->event_loop()->node())
1295 << " Now " << monotonic_now << " trying to send "
1296 << channel_timestamp.monotonic_event_time << " failure "
1297 << state->DebugString();
1298 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001299
Austin Schuh6f3babe2020-01-26 20:34:50 -08001300 if (channel_timestamp.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001301 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001302 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001303 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001304 !state->at_end()) ||
Austin Schuh05b70472020-01-01 17:11:17 -08001305 channel_data.message().data() != nullptr) {
1306 CHECK(channel_data.message().data() != nullptr)
1307 << ": Got a message without data. Forwarding entry which was "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001308 "not matched? Use --skip_missing_forwarding_entries to "
Brian Silverman87ac0402020-09-17 14:47:01 -07001309 "ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001310
Austin Schuh2f8fd752020-09-01 22:38:28 -07001311 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001312 // Confirm that the message was sent on the sending node before the
1313 // destination node (this node). As a proxy, do this by making sure
1314 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001315 if (!FLAGS_skip_order_validation) {
1316 CHECK_LT(channel_timestamp.monotonic_remote_time,
1317 state->monotonic_remote_now(channel_index))
1318 << state->event_loop()->node()->name()->string_view() << " to "
1319 << state->remote_node(channel_index)->name()->string_view()
1320 << " " << state->DebugString();
1321 } else if (channel_timestamp.monotonic_remote_time >=
1322 state->monotonic_remote_now(channel_index)) {
1323 LOG(WARNING)
1324 << "Check failed: channel_timestamp.monotonic_remote_time < "
1325 "state->monotonic_remote_now(channel_index) ("
1326 << channel_timestamp.monotonic_remote_time << " vs. "
1327 << state->monotonic_remote_now(channel_index) << ") "
1328 << state->event_loop()->node()->name()->string_view() << " to "
1329 << state->remote_node(channel_index)->name()->string_view()
1330 << " currently " << channel_timestamp.monotonic_event_time
1331 << " ("
1332 << state->ToDistributedClock(
1333 channel_timestamp.monotonic_event_time)
1334 << ") remote event time "
1335 << channel_timestamp.monotonic_remote_time << " ("
1336 << state->RemoteToDistributedClock(
1337 channel_index, channel_timestamp.monotonic_remote_time)
1338 << ") " << state->DebugString();
1339 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001340
1341 if (FLAGS_timestamps_to_csv) {
1342 if (offset_fp_ == nullptr) {
1343 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1344 fprintf(
1345 offset_fp_,
1346 "# time_since_start, offset node 0, offset node 1, ...\n");
1347 first_time_ = channel_timestamp.realtime_event_time;
1348 }
1349
1350 fprintf(offset_fp_, "%.9f",
1351 std::chrono::duration_cast<std::chrono::duration<double>>(
1352 channel_timestamp.realtime_event_time - first_time_)
1353 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1355 fprintf(offset_fp_, ", %.9f",
1356 time_offset_matrix_(i, 0) +
1357 time_slope_matrix_(i, 0) *
1358 chrono::duration<double>(
1359 event_loop_factory_->distributed_now()
1360 .time_since_epoch())
1361 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001362 }
1363 fprintf(offset_fp_, "\n");
1364 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001365 }
1366
Austin Schuh15649d62019-12-28 16:36:38 -08001367 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh858c9f32020-08-31 16:56:12 -07001368 state->SetRealtimeOffset(channel_timestamp.monotonic_event_time,
1369 channel_timestamp.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001370
Austin Schuh2f8fd752020-09-01 22:38:28 -07001371 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
1372 << channel_timestamp.monotonic_event_time;
1373 // TODO(austin): std::move channel_data in and make that efficient in
1374 // simulation.
Austin Schuh858c9f32020-08-31 16:56:12 -07001375 state->Send(channel_index, channel_data.message().data()->Data(),
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001376 channel_data.message().data()->size(), channel_timestamp);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001377 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001378 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001379 // reading the rest of the log file and call it quits. We don't want
1380 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001381 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1382 bool update_time_dummy;
1383 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001384 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001385 } else {
1386 CHECK(channel_data.message().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001387 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001388 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001389 LOG(WARNING)
1390 << "Not sending data from before the start of the log file. "
1391 << channel_timestamp.monotonic_event_time.time_since_epoch().count()
1392 << " start " << monotonic_start_time().time_since_epoch().count()
1393 << " " << FlatbufferToJson(channel_data);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001394 }
1395
Austin Schuh858c9f32020-08-31 16:56:12 -07001396 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001397 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001398 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1399 << "wakeup for " << next_time << "("
1400 << state->ToDistributedClock(next_time)
1401 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001402 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001403 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001404 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1405 << "No next message, scheduling shutdown";
1406 // Set a timer up immediately after now to die. If we don't do this,
1407 // then the senders waiting on the message we just read will never get
1408 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001409 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001410 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1411 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001412 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001413 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001414
Austin Schuh2f8fd752020-09-01 22:38:28 -07001415 // Once we make this call, the current time changes. So do everything
1416 // which involves time before changing it. That especially includes
1417 // sending the message.
1418 if (update_time) {
1419 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1420 << "updating offsets";
1421
1422 std::vector<aos::monotonic_clock::time_point> before_times;
1423 before_times.resize(states_.size());
1424 std::transform(states_.begin(), states_.end(), before_times.begin(),
1425 [](const std::unique_ptr<State> &state) {
1426 return state->monotonic_now();
1427 });
1428
1429 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001430 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1431 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001432 }
1433
Austin Schuh8bd96322020-02-13 21:18:22 -08001434 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001435 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1436 << state->monotonic_now();
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()) << "after "
1440 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001441 }
1442
1443 // TODO(austin): We should be perfect.
1444 const std::chrono::nanoseconds kTolerance{3};
1445 if (!FLAGS_skip_order_validation) {
1446 CHECK_GE(next_time, state->monotonic_now())
1447 << ": Time skipped the next event.";
1448
1449 for (size_t i = 0; i < states_.size(); ++i) {
1450 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1451 << ": Time changed too much on node "
1452 << MaybeNodeName(states_[i]->event_loop()->node());
1453 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1454 << ": Time changed too much on node "
1455 << states_[i]->event_loop()->node()->name()->string_view();
1456 }
1457 } else {
1458 if (next_time < state->monotonic_now()) {
1459 LOG(WARNING) << "Check failed: next_time >= "
1460 "state->monotonic_now() ("
1461 << next_time << " vs. " << state->monotonic_now()
1462 << "): Time skipped the next event.";
1463 }
1464 for (size_t i = 0; i < states_.size(); ++i) {
1465 if (states_[i]->monotonic_now() >= before_times[i] - kTolerance) {
1466 LOG(WARNING) << "Check failed: "
1467 "states_[i]->monotonic_now() "
1468 ">= before_times[i] - kTolerance ("
1469 << states_[i]->monotonic_now() << " vs. "
1470 << before_times[i] - kTolerance
1471 << ") : Time changed too much on node "
1472 << MaybeNodeName(states_[i]->event_loop()->node());
1473 }
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 }
1484 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001485 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001486
1487 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1488 << state->event_loop()->context().monotonic_event_time << " now "
1489 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001490 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001491
Austin Schuh6f3babe2020-01-26 20:34:50 -08001492 ++live_nodes_;
1493
Austin Schuh858c9f32020-08-31 16:56:12 -07001494 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1495 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001496 }
1497}
1498
1499void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001500 // Make sure that things get destroyed in the correct order, rather than
1501 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001502 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001503 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001504 }
Austin Schuh92547522019-12-28 14:33:43 -08001505
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001506 event_loop_factory_unique_ptr_.reset();
1507 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001508}
1509
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001510void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1511 std::string_view add_prefix) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001512 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1513 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1514 if (channel->name()->str() == name &&
1515 channel->type()->string_view() == type) {
1516 CHECK_EQ(0u, remapped_channels_.count(ii))
1517 << "Already remapped channel "
1518 << configuration::CleanedChannelToString(channel);
1519 remapped_channels_[ii] = std::string(add_prefix) + std::string(name);
1520 VLOG(1) << "Remapping channel "
1521 << configuration::CleanedChannelToString(channel)
1522 << " to have name " << remapped_channels_[ii];
Austin Schuh6331ef92020-01-07 18:28:09 -08001523 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001524 return;
1525 }
1526 }
1527 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1528 << type;
1529}
1530
Austin Schuh01b4c352020-09-21 23:09:39 -07001531void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1532 const Node *node,
1533 std::string_view add_prefix) {
1534 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1535 const Channel *remapped_channel =
1536 configuration::GetChannel(logged_configuration(), name, type, "", node);
1537 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1538 << "\", \"type\": \"" << type << "\"}";
1539 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1540 << "\"}";
1541 VLOG(1) << "Remapped "
1542 << aos::configuration::StrippedChannelToString(remapped_channel);
1543
1544 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1545 // we want it to degrade if the heuristics fail to just work.
1546 //
1547 // The easiest way to do this is going to be incredibly specific and verbose.
1548 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1549 // /original/0/spray. Then, create a map from /original/spray to
1550 // /original/0/spray for just the type we were asked for.
1551 if (name != remapped_channel->name()->string_view()) {
1552 MapT new_map;
1553 new_map.match = std::make_unique<ChannelT>();
1554 new_map.match->name = absl::StrCat(add_prefix, name);
1555 new_map.match->type = type;
1556 if (node != nullptr) {
1557 new_map.match->source_node = node->name()->str();
1558 }
1559 new_map.rename = std::make_unique<ChannelT>();
1560 new_map.rename->name =
1561 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1562 maps_.emplace_back(std::move(new_map));
1563 }
1564
1565 const size_t channel_index =
1566 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1567 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1568 << "Already remapped channel "
1569 << configuration::CleanedChannelToString(remapped_channel);
1570 remapped_channels_[channel_index] =
1571 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1572 MakeRemappedConfig();
1573}
1574
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001575void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001576 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001577 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001578 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001579 << ": Can't change the mapping after the events are scheduled.";
1580 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001581 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001582
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001583 // If no remapping occurred and we are using the original config, then there
1584 // is nothing interesting to do here.
1585 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001586 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001587 return;
1588 }
1589 // Config to copy Channel definitions from. Use the specified
1590 // replay_configuration_ if it has been provided.
1591 const Configuration *const base_config = replay_configuration_ == nullptr
1592 ? logged_configuration()
1593 : replay_configuration_;
1594 // The remapped config will be identical to the base_config, except that it
1595 // will have a bunch of extra channels in the channel list, which are exact
1596 // copies of the remapped channels, but with different names.
1597 // Because the flatbuffers API is a pain to work with, this requires a bit of
1598 // a song-and-dance to get copied over.
1599 // The order of operations is to:
1600 // 1) Make a flatbuffer builder for a config that will just contain a list of
1601 // the new channels that we want to add.
1602 // 2) For each channel that we are remapping:
1603 // a) Make a buffer/builder and construct into it a Channel table that only
1604 // contains the new name for the channel.
1605 // b) Merge the new channel with just the name into the channel that we are
1606 // trying to copy, built in the flatbuffer builder made in 1. This gives
1607 // us the new channel definition that we need.
1608 // 3) Using this list of offsets, build the Configuration of just new
1609 // Channels.
1610 // 4) Merge the Configuration with the new Channels into the base_config.
1611 // 5) Call MergeConfiguration() on that result to give MergeConfiguration a
1612 // chance to sanitize the config.
1613
1614 // This is the builder that we use for the config containing all the new
1615 // channels.
1616 flatbuffers::FlatBufferBuilder new_config_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001617 new_config_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001618 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
1619 for (auto &pair : remapped_channels_) {
1620 // This is the builder that we use for creating the Channel with just the
1621 // new name.
1622 flatbuffers::FlatBufferBuilder new_name_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001623 new_name_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001624 const flatbuffers::Offset<flatbuffers::String> name_offset =
1625 new_name_fbb.CreateString(pair.second);
1626 ChannelBuilder new_name_builder(new_name_fbb);
1627 new_name_builder.add_name(name_offset);
1628 new_name_fbb.Finish(new_name_builder.Finish());
1629 const FlatbufferDetachedBuffer<Channel> new_name = new_name_fbb.Release();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001630 // Retrieve the channel that we want to copy, confirming that it is
1631 // actually present in base_config.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001632 const Channel *const base_channel = CHECK_NOTNULL(configuration::GetChannel(
1633 base_config, logged_configuration()->channels()->Get(pair.first), "",
1634 nullptr));
1635 // Actually create the new channel and put it into the vector of Offsets
1636 // that we will use to create the new Configuration.
1637 channel_offsets.emplace_back(MergeFlatBuffers<Channel>(
1638 reinterpret_cast<const flatbuffers::Table *>(base_channel),
1639 reinterpret_cast<const flatbuffers::Table *>(&new_name.message()),
1640 &new_config_fbb));
1641 }
1642 // Create the Configuration containing the new channels that we want to add.
Austin Schuh01b4c352020-09-21 23:09:39 -07001643 const auto new_channel_vector_offsets =
Austin Schuhfa895892020-01-07 20:07:41 -08001644 new_config_fbb.CreateVector(channel_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001645
1646 // Now create the new maps.
1647 std::vector<flatbuffers::Offset<Map>> map_offsets;
1648 for (const MapT &map : maps_) {
1649 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
1650 new_config_fbb.CreateString(map.match->name);
1651 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
1652 new_config_fbb.CreateString(map.match->type);
1653 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1654 new_config_fbb.CreateString(map.rename->name);
1655 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1656 if (!map.match->source_node.empty()) {
1657 match_source_node_offset =
1658 new_config_fbb.CreateString(map.match->source_node);
1659 }
1660 Channel::Builder match_builder(new_config_fbb);
1661 match_builder.add_name(match_name_offset);
1662 match_builder.add_type(match_type_offset);
1663 if (!map.match->source_node.empty()) {
1664 match_builder.add_source_node(match_source_node_offset);
1665 }
1666 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1667
1668 Channel::Builder rename_builder(new_config_fbb);
1669 rename_builder.add_name(rename_name_offset);
1670 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1671
1672 Map::Builder map_builder(new_config_fbb);
1673 map_builder.add_match(match_offset);
1674 map_builder.add_rename(rename_offset);
1675 map_offsets.emplace_back(map_builder.Finish());
1676 }
1677
1678 const auto new_maps_offsets = new_config_fbb.CreateVector(map_offsets);
1679
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001680 ConfigurationBuilder new_config_builder(new_config_fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001681 new_config_builder.add_channels(new_channel_vector_offsets);
1682 new_config_builder.add_maps(new_maps_offsets);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001683 new_config_fbb.Finish(new_config_builder.Finish());
1684 const FlatbufferDetachedBuffer<Configuration> new_name_config =
1685 new_config_fbb.Release();
1686 // Merge the new channels configuration into the base_config, giving us the
1687 // remapped configuration.
1688 remapped_configuration_buffer_ =
1689 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1690 MergeFlatBuffers<Configuration>(base_config,
1691 &new_name_config.message()));
1692 // Call MergeConfiguration to deal with sanitizing the config.
1693 remapped_configuration_buffer_ =
1694 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1695 configuration::MergeConfiguration(*remapped_configuration_buffer_));
1696
1697 remapped_configuration_ = &remapped_configuration_buffer_->message();
1698}
1699
Austin Schuh6f3babe2020-01-26 20:34:50 -08001700const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1701 const Channel *channel) {
1702 std::string_view channel_name = channel->name()->string_view();
1703 std::string_view channel_type = channel->type()->string_view();
1704 const int channel_index =
1705 configuration::ChannelIndex(logged_configuration(), channel);
1706 // If the channel is remapped, find the correct channel name to use.
1707 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001708 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001709 << configuration::CleanedChannelToString(channel);
1710 channel_name = remapped_channels_[channel_index];
1711 }
1712
Austin Schuhee711052020-08-24 16:06:09 -07001713 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001714 const Channel *remapped_channel = configuration::GetChannel(
1715 event_loop->configuration(), channel_name, channel_type,
1716 event_loop->name(), event_loop->node());
1717
1718 CHECK(remapped_channel != nullptr)
1719 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1720 << channel_type << "\"} because it is not in the provided configuration.";
1721
1722 return remapped_channel;
1723}
1724
Austin Schuh858c9f32020-08-31 16:56:12 -07001725LogReader::State::State(std::unique_ptr<ChannelMerger> channel_merger)
1726 : channel_merger_(std::move(channel_merger)) {}
1727
1728EventLoop *LogReader::State::SetNodeEventLoopFactory(
1729 NodeEventLoopFactory *node_event_loop_factory) {
1730 node_event_loop_factory_ = node_event_loop_factory;
1731 event_loop_unique_ptr_ =
1732 node_event_loop_factory_->MakeEventLoop("log_reader");
1733 return event_loop_unique_ptr_.get();
1734}
1735
1736void LogReader::State::SetChannelCount(size_t count) {
1737 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001738 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001739 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001740 channel_source_state_.resize(count);
1741 factory_channel_index_.resize(count);
1742 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001743}
1744
1745void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001746 size_t logged_channel_index, size_t factory_channel_index,
1747 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001748 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001749 aos::Sender<MessageHeader> *remote_timestamp_sender, State *source_state) {
1750 channels_[logged_channel_index] = std::move(sender);
1751 filters_[logged_channel_index] = filter;
1752 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1753
1754 if (source_state) {
1755 channel_source_state_[logged_channel_index] = source_state;
1756
1757 if (remote_timestamp_sender != nullptr) {
1758 source_state->queue_index_map_[logged_channel_index] =
1759 std::make_unique<std::vector<State::SentTimestamp>>();
1760 }
1761 }
1762
1763 factory_channel_index_[logged_channel_index] = factory_channel_index;
1764}
1765
1766bool LogReader::State::Send(
1767 size_t channel_index, const void *data, size_t size,
1768 const TimestampMerger::DeliveryTimestamp &delivery_timestamp) {
1769 aos::RawSender *sender = channels_[channel_index].get();
1770 uint32_t remote_queue_index = 0xffffffff;
1771
1772 if (remote_timestamp_senders_[channel_index] != nullptr) {
1773 std::vector<SentTimestamp> *queue_index_map =
1774 CHECK_NOTNULL(CHECK_NOTNULL(channel_source_state_[channel_index])
1775 ->queue_index_map_[channel_index]
1776 .get());
1777
1778 SentTimestamp search;
1779 search.monotonic_event_time = delivery_timestamp.monotonic_remote_time;
1780 search.realtime_event_time = delivery_timestamp.realtime_remote_time;
1781 search.queue_index = delivery_timestamp.remote_queue_index;
1782
1783 // Find the sent time if available.
1784 auto element = std::lower_bound(
1785 queue_index_map->begin(), queue_index_map->end(), search,
1786 [](SentTimestamp a, SentTimestamp b) {
1787 if (b.monotonic_event_time < a.monotonic_event_time) {
1788 return false;
1789 }
1790 if (b.monotonic_event_time > a.monotonic_event_time) {
1791 return true;
1792 }
1793
1794 if (b.queue_index < a.queue_index) {
1795 return false;
1796 }
1797 if (b.queue_index > a.queue_index) {
1798 return true;
1799 }
1800
1801 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1802 return false;
1803 });
1804
1805 // TODO(austin): Be a bit more principled here, but we will want to do that
1806 // after the logger rewrite. We hit this when one node finishes, but the
1807 // other node isn't done yet. So there is no send time, but there is a
1808 // receive time.
1809 if (element != queue_index_map->end()) {
1810 CHECK_EQ(element->monotonic_event_time,
1811 delivery_timestamp.monotonic_remote_time);
1812 CHECK_EQ(element->realtime_event_time,
1813 delivery_timestamp.realtime_remote_time);
1814 CHECK_EQ(element->queue_index, delivery_timestamp.remote_queue_index);
1815
1816 remote_queue_index = element->actual_queue_index;
1817 }
1818 }
1819
1820 // Send! Use the replayed queue index here instead of the logged queue index
1821 // for the remote queue index. This makes re-logging work.
1822 const bool sent =
1823 sender->Send(data, size, delivery_timestamp.monotonic_remote_time,
1824 delivery_timestamp.realtime_remote_time, remote_queue_index);
1825 if (!sent) return false;
1826
1827 if (queue_index_map_[channel_index]) {
1828 SentTimestamp timestamp;
1829 timestamp.monotonic_event_time = delivery_timestamp.monotonic_event_time;
1830 timestamp.realtime_event_time = delivery_timestamp.realtime_event_time;
1831 timestamp.queue_index = delivery_timestamp.queue_index;
1832 timestamp.actual_queue_index = sender->sent_queue_index();
1833 queue_index_map_[channel_index]->emplace_back(timestamp);
1834 } else if (remote_timestamp_senders_[channel_index] != nullptr) {
1835 aos::Sender<MessageHeader>::Builder builder =
1836 remote_timestamp_senders_[channel_index]->MakeBuilder();
1837
1838 logger::MessageHeader::Builder message_header_builder =
1839 builder.MakeBuilder<logger::MessageHeader>();
1840
1841 message_header_builder.add_channel_index(
1842 factory_channel_index_[channel_index]);
1843
1844 // Swap the remote and sent metrics. They are from the sender's
1845 // perspective, not the receiver's perspective.
1846 message_header_builder.add_monotonic_sent_time(
1847 sender->monotonic_sent_time().time_since_epoch().count());
1848 message_header_builder.add_realtime_sent_time(
1849 sender->realtime_sent_time().time_since_epoch().count());
1850 message_header_builder.add_queue_index(sender->sent_queue_index());
1851
1852 message_header_builder.add_monotonic_remote_time(
1853 delivery_timestamp.monotonic_remote_time.time_since_epoch().count());
1854 message_header_builder.add_realtime_remote_time(
1855 delivery_timestamp.realtime_remote_time.time_since_epoch().count());
1856
1857 message_header_builder.add_remote_queue_index(remote_queue_index);
1858
1859 builder.Send(message_header_builder.Finish());
1860 }
1861
1862 return true;
1863}
1864
1865aos::Sender<MessageHeader> *LogReader::State::RemoteTimestampSender(
1866 const Node *delivered_node) {
1867 auto sender = remote_timestamp_senders_map_.find(delivered_node);
1868
1869 if (sender == remote_timestamp_senders_map_.end()) {
1870 sender = remote_timestamp_senders_map_
1871 .emplace(std::make_pair(
1872 delivered_node,
1873 event_loop()->MakeSender<MessageHeader>(
1874 absl::StrCat("/aos/remote_timestamps/",
1875 delivered_node->name()->string_view()))))
1876 .first;
1877 }
1878
1879 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07001880}
1881
1882std::tuple<TimestampMerger::DeliveryTimestamp, int,
1883 FlatbufferVector<MessageHeader>>
1884LogReader::State::PopOldest(bool *update_time) {
1885 CHECK_GT(sorted_messages_.size(), 0u);
1886
1887 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001888 FlatbufferVector<MessageHeader>,
1889 message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001890 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001891 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001892 << std::get<0>(result).monotonic_event_time;
1893 sorted_messages_.pop_front();
1894 SeedSortedMessages();
1895
Austin Schuh2f8fd752020-09-01 22:38:28 -07001896 if (std::get<3>(result) != nullptr) {
1897 *update_time = std::get<3>(result)->Pop(
1898 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1899 } else {
1900 *update_time = false;
1901 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001902 return std::make_tuple(std::get<0>(result), std::get<1>(result),
1903 std::move(std::get<2>(result)));
1904}
1905
1906monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1907 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001908 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001909 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1910 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1911 }
1912
1913 return channel_merger_->OldestMessageTime();
1914}
1915
1916void LogReader::State::SeedSortedMessages() {
1917 const aos::monotonic_clock::time_point end_queue_time =
1918 (sorted_messages_.size() > 0
1919 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
1920 : channel_merger_->monotonic_start_time()) +
1921 std::chrono::seconds(2);
1922
1923 while (true) {
1924 if (channel_merger_->OldestMessageTime() == monotonic_clock::max_time) {
1925 return;
1926 }
1927 if (sorted_messages_.size() > 0) {
1928 // Stop placing sorted messages on the list once we have 2 seconds
1929 // queued up (but queue at least until the log starts.
1930 if (end_queue_time <
1931 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
1932 return;
1933 }
1934 }
1935
1936 TimestampMerger::DeliveryTimestamp channel_timestamp;
1937 int channel_index;
1938 FlatbufferVector<MessageHeader> channel_data =
1939 FlatbufferVector<MessageHeader>::Empty();
1940
Austin Schuh2f8fd752020-09-01 22:38:28 -07001941 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
1942
Austin Schuh858c9f32020-08-31 16:56:12 -07001943 std::tie(channel_timestamp, channel_index, channel_data) =
1944 channel_merger_->PopOldest();
1945
Austin Schuh2f8fd752020-09-01 22:38:28 -07001946 // Skip any messages without forwarding information.
1947 if (channel_timestamp.monotonic_remote_time != monotonic_clock::min_time) {
1948 // Got a forwarding timestamp!
1949 filter = filters_[channel_index];
1950
1951 CHECK(filter != nullptr);
1952
1953 // Call the correct method depending on if we are the forward or
1954 // reverse direction here.
1955 filter->Sample(event_loop_->node(),
1956 channel_timestamp.monotonic_event_time,
1957 channel_timestamp.monotonic_remote_time);
1958 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001959 sorted_messages_.emplace_back(channel_timestamp, channel_index,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001960 std::move(channel_data), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07001961 }
1962}
1963
1964void LogReader::State::Deregister() {
1965 for (size_t i = 0; i < channels_.size(); ++i) {
1966 channels_[i].reset();
1967 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001968 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07001969 event_loop_unique_ptr_.reset();
1970 event_loop_ = nullptr;
1971 timer_handler_ = nullptr;
1972 node_event_loop_factory_ = nullptr;
1973}
1974
Austin Schuhe309d2a2019-11-29 13:25:21 -08001975} // namespace logger
1976} // namespace aos