blob: 19a022937703b3b148903eb937d676cc0fe84330 [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"
James Kuszmaul38735e82019-12-07 16:42:06 -080014#include "aos/events/logging/logger_generated.h"
Austin Schuh64fab802020-09-09 22:47:47 -070015#include "aos/events/logging/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080016#include "aos/flatbuffer_merge.h"
Austin Schuh288479d2019-12-18 19:47:52 -080017#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080018#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070019#include "aos/util/file.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080020#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070021#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022
Austin Schuh15649d62019-12-28 16:36:38 -080023DEFINE_bool(skip_missing_forwarding_entries, false,
24 "If true, drop any forwarding entries with missing data. If "
25 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080026
Austin Schuh8bd96322020-02-13 21:18:22 -080027DEFINE_bool(timestamps_to_csv, false,
28 "If true, write all the time synchronization information to a set "
29 "of CSV files in /tmp/. This should only be needed when debugging "
30 "time synchronization.");
31
Austin Schuh2f8fd752020-09-01 22:38:28 -070032DEFINE_bool(skip_order_validation, false,
33 "If true, ignore any out of orderness in replay");
34
Austin Schuhe309d2a2019-11-29 13:25:21 -080035namespace aos {
36namespace logger {
Austin Schuhe309d2a2019-11-29 13:25:21 -080037namespace chrono = std::chrono;
38
Brian Silverman1f345222020-09-24 21:14:48 -070039Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
40 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -080041 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -070042 configuration_(configuration),
Brian Silvermanae7c0332020-09-30 16:58:23 -070043 boot_uuid_(
44 util::ReadFileToStringOrDie("/proc/sys/kernel/random/boot_id")),
Austin Schuh0c297012020-09-16 18:41:59 -070045 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -070046 timer_handler_(event_loop_->AddTimer(
47 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -070048 server_statistics_fetcher_(
49 configuration::MultiNode(event_loop_->configuration())
50 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
51 "/aos")
52 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -070053 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070054
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070055 // Find all the nodes which are logging timestamps on our node. This may
56 // over-estimate if should_log is specified.
57 std::vector<const Node *> timestamp_logger_nodes =
58 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070059
60 std::map<const Channel *, const Node *> timestamp_logger_channels;
61
62 // Now that we have all the nodes accumulated, make remote timestamp loggers
63 // for them.
64 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070065 // Note: since we are doing a find using the event loop channel, we need to
66 // make sure this channel pointer is part of the event loop configuration,
67 // not configuration_. This only matters when configuration_ !=
68 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -070069 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070070 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -070071 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
72 logger::MessageHeader::GetFullyQualifiedName(), event_loop_->name(),
73 event_loop_->node());
74
75 CHECK(channel != nullptr)
76 << ": Remote timestamps are logged on "
77 << event_loop_->node()->name()->string_view()
78 << " but can't find channel /aos/remote_timestamps/"
79 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -070080 if (!should_log(channel)) {
81 continue;
82 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070083 timestamp_logger_channels.insert(std::make_pair(channel, node));
84 }
85
Brian Silvermand90905f2020-09-23 14:42:56 -070086 const size_t our_node_index =
87 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -070088
Brian Silverman1f345222020-09-24 21:14:48 -070089 for (size_t channel_index = 0;
90 channel_index < configuration_->channels()->size(); ++channel_index) {
91 const Channel *const config_channel =
92 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -070093 // The MakeRawFetcher method needs a channel which is in the event loop
94 // configuration() object, not the configuration_ object. Go look that up
95 // from the config.
96 const Channel *channel = aos::configuration::GetChannel(
97 event_loop_->configuration(), config_channel->name()->string_view(),
98 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -070099 CHECK(channel != nullptr)
100 << ": Failed to look up channel "
101 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700102 if (!should_log(channel)) {
103 continue;
104 }
Austin Schuh0c297012020-09-16 18:41:59 -0700105
Austin Schuhe309d2a2019-11-29 13:25:21 -0800106 FetcherStruct fs;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700107 fs.node_index = our_node_index;
Brian Silverman1f345222020-09-24 21:14:48 -0700108 fs.channel_index = channel_index;
109 fs.channel = channel;
110
Austin Schuh6f3babe2020-01-26 20:34:50 -0800111 const bool is_local =
112 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
113
Austin Schuh15649d62019-12-28 16:36:38 -0800114 const bool is_readable =
115 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700116 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
117 channel, event_loop_->node());
118 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800119
Brian Silverman1f345222020-09-24 21:14:48 -0700120 bool log_delivery_times = false;
121 if (event_loop_->node() != nullptr) {
122 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
123 channel, event_loop_->node(), event_loop_->node());
124 }
Austin Schuh15649d62019-12-28 16:36:38 -0800125
Austin Schuh2f8fd752020-09-01 22:38:28 -0700126 // Now, detect a MessageHeader timestamp logger where we should just log the
127 // contents to a file directly.
128 const bool log_contents = timestamp_logger_channels.find(channel) !=
129 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700130
131 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800132 fs.fetcher = event_loop->MakeRawFetcher(channel);
133 VLOG(1) << "Logging channel "
134 << configuration::CleanedChannelToString(channel);
135
136 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800137 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700138 fs.wants_timestamp_writer = true;
Austin Schuh15649d62019-12-28 16:36:38 -0800139 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800140 if (log_message) {
141 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700142 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800143 if (!is_local) {
144 fs.log_type = LogType::kLogRemoteMessage;
145 }
146 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147 if (log_contents) {
148 VLOG(1) << "Timestamp logger channel "
149 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700150 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
151 fs.wants_contents_writer = true;
Austin Schuh0c297012020-09-16 18:41:59 -0700152 fs.node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700153 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700154 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800155 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800156 }
Brian Silverman1f345222020-09-24 21:14:48 -0700157 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700158
159 // When we are logging remote timestamps, we need to be able to translate from
160 // the channel index that the event loop uses to the channel index in the
161 // config in the log file.
162 event_loop_to_logged_channel_index_.resize(
163 event_loop->configuration()->channels()->size(), -1);
164 for (size_t event_loop_channel_index = 0;
165 event_loop_channel_index <
166 event_loop->configuration()->channels()->size();
167 ++event_loop_channel_index) {
168 const Channel *event_loop_channel =
169 event_loop->configuration()->channels()->Get(event_loop_channel_index);
170
171 const Channel *logged_channel = aos::configuration::GetChannel(
172 configuration_, event_loop_channel->name()->string_view(),
173 event_loop_channel->type()->string_view(), "",
174 configuration::GetNode(configuration_, event_loop_->node()));
175
176 if (logged_channel != nullptr) {
177 event_loop_to_logged_channel_index_[event_loop_channel_index] =
178 configuration::ChannelIndex(configuration_, logged_channel);
179 }
180 }
Brian Silverman1f345222020-09-24 21:14:48 -0700181}
182
183Logger::~Logger() {
184 if (log_namer_) {
185 // If we are replaying a log file, or in simulation, we want to force the
186 // last bit of data to be logged. The easiest way to deal with this is to
187 // poll everything as we go to destroy the class, ie, shut down the logger,
188 // and write it to disk.
189 StopLogging(event_loop_->monotonic_now());
190 }
191}
192
Brian Silvermanae7c0332020-09-30 16:58:23 -0700193void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
194 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700195 CHECK(!log_namer_) << ": Already logging";
196 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700197 log_event_uuid_ = UUID::Random();
198 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700199 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
200
201 // We want to do as much work as possible before the initial Fetch. Time
202 // between that and actually starting to log opens up the possibility of
203 // falling off the end of the queue during that time.
204
205 for (FetcherStruct &f : fetchers_) {
206 if (f.wants_writer) {
207 f.writer = log_namer_->MakeWriter(f.channel);
208 }
209 if (f.wants_timestamp_writer) {
210 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
211 }
212 if (f.wants_contents_writer) {
213 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
214 f.channel, CHECK_NOTNULL(f.timestamp_node));
215 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800216 }
217
Brian Silverman1f345222020-09-24 21:14:48 -0700218 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700219 node_state_.resize(configuration::MultiNode(configuration_)
220 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700221 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800222
Austin Schuh2f8fd752020-09-01 22:38:28 -0700223 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700224 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800225
Austin Schuh2f8fd752020-09-01 22:38:28 -0700226 node_state_[node_index].log_file_header = MakeHeader(node);
227 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800228
Austin Schuh2f8fd752020-09-01 22:38:28 -0700229 // Grab data from each channel right before we declare the log file started
230 // so we can capture the latest message on each channel. This lets us have
231 // non periodic messages with configuration that now get logged.
232 for (FetcherStruct &f : fetchers_) {
233 f.written = !f.fetcher->Fetch();
234 }
235
236 // Clear out any old timestamps in case we are re-starting logging.
237 for (size_t i = 0; i < node_state_.size(); ++i) {
238 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time);
239 }
240
241 WriteHeader();
242
243 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
244 << " start_time " << last_synchronized_time_;
245
246 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
247 polling_period_);
248}
249
Brian Silverman1f345222020-09-24 21:14:48 -0700250std::unique_ptr<LogNamer> Logger::StopLogging(
251 aos::monotonic_clock::time_point end_time) {
252 CHECK(log_namer_) << ": Not logging right now";
253
254 if (end_time != aos::monotonic_clock::min_time) {
255 LogUntil(end_time);
256 }
257 timer_handler_->Disable();
258
259 for (FetcherStruct &f : fetchers_) {
260 f.writer = nullptr;
261 f.timestamp_writer = nullptr;
262 f.contents_writer = nullptr;
263 }
264 node_state_.clear();
265
Brian Silvermanae7c0332020-09-30 16:58:23 -0700266 log_event_uuid_ = UUID::Zero();
267 log_start_uuid_ = std::string();
268
Brian Silverman1f345222020-09-24 21:14:48 -0700269 return std::move(log_namer_);
270}
271
Austin Schuhfa895892020-01-07 20:07:41 -0800272void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700273 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700274 server_statistics_fetcher_.Fetch();
275 }
276
277 aos::monotonic_clock::time_point monotonic_start_time =
278 event_loop_->monotonic_now();
279 aos::realtime_clock::time_point realtime_start_time =
280 event_loop_->realtime_now();
281
282 // We need to pick a point in time to declare the log file "started". This
283 // starts here. It needs to be after everything is fetched so that the
284 // fetchers are all pointed at the most recent message before the start
285 // time.
286 last_synchronized_time_ = monotonic_start_time;
287
Austin Schuh6f3babe2020-01-26 20:34:50 -0800288 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700289 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700290 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
291 realtime_start_time);
Austin Schuh64fab802020-09-09 22:47:47 -0700292 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800293 }
294}
Austin Schuh8bd96322020-02-13 21:18:22 -0800295
Austin Schuh2f8fd752020-09-01 22:38:28 -0700296void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700297 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700298 server_statistics_fetcher_.Fetch();
299 } else {
300 return;
301 }
302
303 if (server_statistics_fetcher_.get() == nullptr) {
304 return;
305 }
306
307 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700308 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700309 if (MaybeUpdateTimestamp(
310 node, node_index,
311 server_statistics_fetcher_.context().monotonic_event_time,
312 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh64fab802020-09-09 22:47:47 -0700313 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700314 }
315 }
316}
317
318void Logger::SetStartTime(size_t node_index,
319 aos::monotonic_clock::time_point monotonic_start_time,
320 aos::realtime_clock::time_point realtime_start_time) {
321 node_state_[node_index].monotonic_start_time = monotonic_start_time;
322 node_state_[node_index].realtime_start_time = realtime_start_time;
323 node_state_[node_index]
324 .log_file_header.mutable_message()
325 ->mutate_monotonic_start_time(
326 std::chrono::duration_cast<std::chrono::nanoseconds>(
327 monotonic_start_time.time_since_epoch())
328 .count());
329 if (node_state_[node_index]
330 .log_file_header.mutable_message()
331 ->has_realtime_start_time()) {
332 node_state_[node_index]
333 .log_file_header.mutable_message()
334 ->mutate_realtime_start_time(
335 std::chrono::duration_cast<std::chrono::nanoseconds>(
336 realtime_start_time.time_since_epoch())
337 .count());
338 }
339}
340
341bool Logger::MaybeUpdateTimestamp(
342 const Node *node, int node_index,
343 aos::monotonic_clock::time_point monotonic_start_time,
344 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700345 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700346 if (node_state_[node_index].monotonic_start_time !=
347 monotonic_clock::min_time) {
348 return false;
349 }
Austin Schuh0c297012020-09-16 18:41:59 -0700350 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700351 if (event_loop_->node() == node) {
352 // There are no offsets to compute for ourself, so always succeed.
353 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
354 return true;
355 } else if (server_statistics_fetcher_.get() != nullptr) {
356 // We must be a remote node now. Look for the connection and see if it is
357 // connected.
358
359 for (const message_bridge::ServerConnection *connection :
360 *server_statistics_fetcher_->connections()) {
361 if (connection->node()->name()->string_view() !=
362 node->name()->string_view()) {
363 continue;
364 }
365
366 if (connection->state() != message_bridge::State::CONNECTED) {
367 VLOG(1) << node->name()->string_view()
368 << " is not connected, can't start it yet.";
369 break;
370 }
371
372 if (!connection->has_monotonic_offset()) {
373 VLOG(1) << "Missing monotonic offset for setting start time for node "
374 << aos::FlatbufferToJson(node);
375 break;
376 }
377
378 VLOG(1) << "Updating start time for " << aos::FlatbufferToJson(node);
379
380 // Found it and it is connected. Compensate and go.
381 monotonic_start_time +=
382 std::chrono::nanoseconds(connection->monotonic_offset());
383
384 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
385 return true;
386 }
387 }
388 } else {
389 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
390 return true;
391 }
392 return false;
393}
394
395aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
396 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800397 // Now write the header with this timestamp in it.
398 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800399 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800400
Austin Schuh2f8fd752020-09-01 22:38:28 -0700401 // TODO(austin): Compress this much more efficiently. There are a bunch of
402 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700403 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700404 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800405
Brian Silvermanae7c0332020-09-30 16:58:23 -0700406 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700407 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800408
Brian Silvermanae7c0332020-09-30 16:58:23 -0700409 CHECK(log_event_uuid_ != UUID::Zero());
410 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
411 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700412
Brian Silvermanae7c0332020-09-30 16:58:23 -0700413 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
414 fbb.CreateString(logger_instance_uuid_.string_view());
415
416 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
417 if (!log_start_uuid_.empty()) {
418 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
419 }
420
421 const flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
422 fbb.CreateString(boot_uuid_);
423
424 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700425 fbb.CreateString("00000000-0000-4000-8000-000000000000");
426
Austin Schuhfa895892020-01-07 20:07:41 -0800427 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700428 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700429
Austin Schuh0c297012020-09-16 18:41:59 -0700430 if (configuration::MultiNode(configuration_)) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800431 node_offset = CopyFlatBuffer(node, &fbb);
Brian Silverman80993c22020-10-01 15:05:19 -0700432 logger_node_offset = CopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800433 }
434
435 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
436
Austin Schuh64fab802020-09-09 22:47:47 -0700437 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800438
439 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800440 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800441 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700442 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800443 }
444
445 log_file_header_builder.add_configuration(configuration_offset);
446 // The worst case theoretical out of order is the polling period times 2.
447 // One message could get logged right after the boundary, but be for right
448 // before the next boundary. And the reverse could happen for another
449 // message. Report back 3x to be extra safe, and because the cost isn't
450 // huge on the read side.
451 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700452 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800453
454 log_file_header_builder.add_monotonic_start_time(
455 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700456 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800457 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700458 if (node == event_loop_->node()) {
459 log_file_header_builder.add_realtime_start_time(
460 std::chrono::duration_cast<std::chrono::nanoseconds>(
461 realtime_clock::min_time.time_since_epoch())
462 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800463 }
464
Brian Silvermanae7c0332020-09-30 16:58:23 -0700465 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
466 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
467 if (!log_start_uuid_offset.IsNull()) {
468 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
469 }
470 log_file_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700471
472 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
473 log_file_header_builder.add_parts_index(0);
474
Austin Schuh2f8fd752020-09-01 22:38:28 -0700475 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
476 return fbb.Release();
477}
478
479void Logger::Rotate() {
480 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700481 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700482 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700483 }
484}
485
486void Logger::LogUntil(monotonic_clock::time_point t) {
487 WriteMissingTimestamps();
488
489 // Write each channel to disk, one at a time.
490 for (FetcherStruct &f : fetchers_) {
491 while (true) {
492 if (f.written) {
493 if (!f.fetcher->FetchNext()) {
494 VLOG(2) << "No new data on "
495 << configuration::CleanedChannelToString(
496 f.fetcher->channel());
497 break;
498 } else {
499 f.written = false;
500 }
501 }
502
503 CHECK(!f.written);
504
505 // TODO(james): Write tests to exercise this logic.
506 if (f.fetcher->context().monotonic_event_time < t) {
507 if (f.writer != nullptr) {
508 // Write!
509 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
510 max_header_size_);
511 fbb.ForceDefaults(true);
512
513 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
514 f.channel_index, f.log_type));
515
516 VLOG(2) << "Writing data as node "
517 << FlatbufferToJson(event_loop_->node()) << " for channel "
518 << configuration::CleanedChannelToString(f.fetcher->channel())
519 << " to " << f.writer->filename() << " data "
520 << FlatbufferToJson(
521 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
522 fbb.GetBufferPointer()));
523
524 max_header_size_ = std::max(
525 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
526 f.writer->QueueSizedFlatbuffer(&fbb);
527 }
528
529 if (f.timestamp_writer != nullptr) {
530 // And now handle timestamps.
531 flatbuffers::FlatBufferBuilder fbb;
532 fbb.ForceDefaults(true);
533
534 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
535 f.channel_index,
536 LogType::kLogDeliveryTimeOnly));
537
538 VLOG(2) << "Writing timestamps as node "
539 << FlatbufferToJson(event_loop_->node()) << " for channel "
540 << configuration::CleanedChannelToString(f.fetcher->channel())
541 << " to " << f.timestamp_writer->filename() << " timestamp "
542 << FlatbufferToJson(
543 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
544 fbb.GetBufferPointer()));
545
546 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
547 }
548
549 if (f.contents_writer != nullptr) {
550 // And now handle the special message contents channel. Copy the
551 // message into a FlatBufferBuilder and save it to disk.
552 // TODO(austin): We can be more efficient here when we start to
553 // care...
554 flatbuffers::FlatBufferBuilder fbb;
555 fbb.ForceDefaults(true);
556
557 const MessageHeader *msg =
558 flatbuffers::GetRoot<MessageHeader>(f.fetcher->context().data);
559
560 logger::MessageHeader::Builder message_header_builder(fbb);
561
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700562 // TODO(austin): This needs to check the channel_index and confirm
563 // that it should be logged before squirreling away the timestamp to
564 // disk. We don't want to log irrelevant timestamps.
565
Austin Schuh2f8fd752020-09-01 22:38:28 -0700566 // Note: this must match the same order as MessageBridgeServer and
567 // PackMessage. We want identical headers to have identical
568 // on-the-wire formats to make comparing them easier.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700569
570 // Translate from the channel index that the event loop uses to the
571 // channel index in the log file.
572 message_header_builder.add_channel_index(
573 event_loop_to_logged_channel_index_[msg->channel_index()]);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700574
575 message_header_builder.add_queue_index(msg->queue_index());
576 message_header_builder.add_monotonic_sent_time(
577 msg->monotonic_sent_time());
578 message_header_builder.add_realtime_sent_time(
579 msg->realtime_sent_time());
580
581 message_header_builder.add_monotonic_remote_time(
582 msg->monotonic_remote_time());
583 message_header_builder.add_realtime_remote_time(
584 msg->realtime_remote_time());
585 message_header_builder.add_remote_queue_index(
586 msg->remote_queue_index());
587
588 fbb.FinishSizePrefixed(message_header_builder.Finish());
589
590 f.contents_writer->QueueSizedFlatbuffer(&fbb);
591 }
592
593 f.written = true;
594 } else {
595 break;
596 }
597 }
598 }
599 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800600}
601
Brian Silverman1f345222020-09-24 21:14:48 -0700602void Logger::DoLogData(const monotonic_clock::time_point end_time) {
603 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800604 // max_out_of_order_duration. To do this, we need sync points. Every write
605 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800606
607 do {
608 // Move the sync point up by at most polling_period. This forces one sync
609 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700610 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
611
612 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800613
Austin Schuhe309d2a2019-11-29 13:25:21 -0800614 // If we missed cycles, we could be pretty far behind. Spin until we are
615 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700616 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800617}
618
Austin Schuh11d43732020-09-21 17:28:30 -0700619std::vector<LogFile> SortParts(const std::vector<std::string> &parts) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700620 // Start by grouping all parts by UUID, and extracting the part index.
Austin Schuh11d43732020-09-21 17:28:30 -0700621 // Datastructure to hold all the info extracted from a set of parts which go
622 // together so we can sort them afterwords.
623 struct UnsortedLogParts {
624 // Start times.
625 aos::monotonic_clock::time_point monotonic_start_time;
626 aos::realtime_clock::time_point realtime_start_time;
627
628 // Node to save.
629 std::string node;
630
631 // Pairs of the filename and the part index for sorting.
632 std::vector<std::pair<std::string, int>> parts;
633 };
634
Brian Silvermanae7c0332020-09-30 16:58:23 -0700635 // Map holding the log_event_uuid -> second map. The second map holds the
Austin Schuh11d43732020-09-21 17:28:30 -0700636 // parts_uuid -> list of parts for sorting.
637 std::map<std::string, std::map<std::string, UnsortedLogParts>> parts_list;
Austin Schuh5212cad2020-09-09 23:12:09 -0700638
639 // Sort part files without UUIDs and part indexes as well. Extract everything
640 // useful from the log in the first pass, then sort later.
Austin Schuh11d43732020-09-21 17:28:30 -0700641 struct UnsortedOldParts {
642 // Part information with everything but the list of parts.
643 LogParts parts;
644
645 // Tuple of time for the data and filename needed for sorting after
646 // extracting.
Brian Silvermand90905f2020-09-23 14:42:56 -0700647 std::vector<std::pair<monotonic_clock::time_point, std::string>>
648 unsorted_parts;
Austin Schuh5212cad2020-09-09 23:12:09 -0700649 };
650
Austin Schuh11d43732020-09-21 17:28:30 -0700651 // A list of all the old parts which we don't know how to sort using uuids.
652 // There are enough of these in the wild that this is worth supporting.
653 std::vector<UnsortedOldParts> old_parts;
Austin Schuh5212cad2020-09-09 23:12:09 -0700654
Austin Schuh11d43732020-09-21 17:28:30 -0700655 // Now extract everything into our datastructures above for sorting.
Austin Schuh5212cad2020-09-09 23:12:09 -0700656 for (const std::string &part : parts) {
657 FlatbufferVector<LogFileHeader> log_header = ReadHeader(part);
658
Austin Schuh11d43732020-09-21 17:28:30 -0700659 const monotonic_clock::time_point monotonic_start_time(
660 chrono::nanoseconds(log_header.message().monotonic_start_time()));
661 const realtime_clock::time_point realtime_start_time(
662 chrono::nanoseconds(log_header.message().realtime_start_time()));
663
664 const std::string_view node =
665 log_header.message().has_node()
666 ? log_header.message().node()->name()->string_view()
667 : "";
668
Austin Schuh5212cad2020-09-09 23:12:09 -0700669 // Looks like an old log. No UUID, index, and also single node. We have
670 // little to no multi-node log files in the wild without part UUIDs and
671 // indexes which we care much about.
672 if (!log_header.message().has_parts_uuid() &&
673 !log_header.message().has_parts_index() &&
674 !log_header.message().has_node()) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700675 FlatbufferVector<MessageHeader> first_message = ReadNthMessage(part, 0);
Austin Schuh11d43732020-09-21 17:28:30 -0700676 const monotonic_clock::time_point first_message_time(
Austin Schuh5212cad2020-09-09 23:12:09 -0700677 chrono::nanoseconds(first_message.message().monotonic_sent_time()));
Austin Schuh11d43732020-09-21 17:28:30 -0700678
679 // Find anything with a matching start time. They all go together.
680 auto result = std::find_if(
681 old_parts.begin(), old_parts.end(),
682 [&](const UnsortedOldParts &parts) {
683 return parts.parts.monotonic_start_time == monotonic_start_time &&
684 parts.parts.realtime_start_time == realtime_start_time;
685 });
686
687 if (result == old_parts.end()) {
688 old_parts.emplace_back();
689 old_parts.back().parts.monotonic_start_time = monotonic_start_time;
690 old_parts.back().parts.realtime_start_time = realtime_start_time;
691 old_parts.back().unsorted_parts.emplace_back(
692 std::make_pair(first_message_time, part));
693 } else {
694 result->unsorted_parts.emplace_back(
695 std::make_pair(first_message_time, part));
696 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700697 continue;
698 }
699
Brian Silvermanae7c0332020-09-30 16:58:23 -0700700 CHECK(log_header.message().has_log_event_uuid());
Austin Schuh5212cad2020-09-09 23:12:09 -0700701 CHECK(log_header.message().has_parts_uuid());
702 CHECK(log_header.message().has_parts_index());
703
Brian Silvermanae7c0332020-09-30 16:58:23 -0700704 const std::string log_event_uuid =
705 log_header.message().log_event_uuid()->str();
Austin Schuh5212cad2020-09-09 23:12:09 -0700706 const std::string parts_uuid = log_header.message().parts_uuid()->str();
Austin Schuh11d43732020-09-21 17:28:30 -0700707 int32_t parts_index = log_header.message().parts_index();
708
Brian Silvermanae7c0332020-09-30 16:58:23 -0700709 auto log_it = parts_list.find(log_event_uuid);
Austin Schuh11d43732020-09-21 17:28:30 -0700710 if (log_it == parts_list.end()) {
Brian Silvermanae7c0332020-09-30 16:58:23 -0700711 log_it =
712 parts_list
713 .insert(std::make_pair(log_event_uuid,
714 std::map<std::string, UnsortedLogParts>()))
715 .first;
Austin Schuh5212cad2020-09-09 23:12:09 -0700716 }
Austin Schuh11d43732020-09-21 17:28:30 -0700717
718 auto it = log_it->second.find(parts_uuid);
719 if (it == log_it->second.end()) {
720 it = log_it->second.insert(std::make_pair(parts_uuid, UnsortedLogParts()))
721 .first;
722 it->second.monotonic_start_time = monotonic_start_time;
723 it->second.realtime_start_time = realtime_start_time;
724 it->second.node = std::string(node);
725 }
726
727 // First part might be min_time. If it is, try to put a better time on it.
728 if (it->second.monotonic_start_time == monotonic_clock::min_time) {
729 it->second.monotonic_start_time = monotonic_start_time;
730 } else if (monotonic_start_time != monotonic_clock::min_time) {
731 CHECK_EQ(it->second.monotonic_start_time, monotonic_start_time);
732 }
733 if (it->second.realtime_start_time == realtime_clock::min_time) {
734 it->second.realtime_start_time = realtime_start_time;
735 } else if (realtime_start_time != realtime_clock::min_time) {
736 CHECK_EQ(it->second.realtime_start_time, realtime_start_time);
737 }
738
739 it->second.parts.emplace_back(std::make_pair(part, parts_index));
Austin Schuh5212cad2020-09-09 23:12:09 -0700740 }
741
742 CHECK_NE(old_parts.empty(), parts_list.empty())
743 << ": Can't have a mix of old and new parts.";
744
Austin Schuh11d43732020-09-21 17:28:30 -0700745 // Now reformat old_parts to be in the right datastructure to report.
Austin Schuh5212cad2020-09-09 23:12:09 -0700746 if (!old_parts.empty()) {
Austin Schuh11d43732020-09-21 17:28:30 -0700747 std::vector<LogFile> result;
748 for (UnsortedOldParts &p : old_parts) {
749 // Sort by the oldest message in each file.
750 std::sort(
751 p.unsorted_parts.begin(), p.unsorted_parts.end(),
752 [](const std::pair<monotonic_clock::time_point, std::string> &a,
753 const std::pair<monotonic_clock::time_point, std::string> &b) {
754 return a.first < b.first;
755 });
756 LogFile log_file;
757 for (std::pair<monotonic_clock::time_point, std::string> &f :
758 p.unsorted_parts) {
759 p.parts.parts.emplace_back(std::move(f.second));
760 }
761 log_file.parts.emplace_back(std::move(p.parts));
762 result.emplace_back(std::move(log_file));
Austin Schuh5212cad2020-09-09 23:12:09 -0700763 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700764
Austin Schuh11d43732020-09-21 17:28:30 -0700765 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700766 }
767
768 // Now, sort them and produce the final vector form.
Austin Schuh11d43732020-09-21 17:28:30 -0700769 std::vector<LogFile> result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700770 result.reserve(parts_list.size());
Brian Silvermand90905f2020-09-23 14:42:56 -0700771 for (std::pair<const std::string, std::map<std::string, UnsortedLogParts>>
772 &logs : parts_list) {
Austin Schuh11d43732020-09-21 17:28:30 -0700773 LogFile new_file;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700774 new_file.log_event_uuid = logs.first;
Austin Schuh11d43732020-09-21 17:28:30 -0700775 for (std::pair<const std::string, UnsortedLogParts> &parts : logs.second) {
776 LogParts new_parts;
777 new_parts.monotonic_start_time = parts.second.monotonic_start_time;
778 new_parts.realtime_start_time = parts.second.realtime_start_time;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700779 new_parts.log_event_uuid = logs.first;
Austin Schuh11d43732020-09-21 17:28:30 -0700780 new_parts.parts_uuid = parts.first;
781 new_parts.node = std::move(parts.second.node);
782
783 std::sort(parts.second.parts.begin(), parts.second.parts.end(),
784 [](const std::pair<std::string, int> &a,
785 const std::pair<std::string, int> &b) {
786 return a.second < b.second;
787 });
788 new_parts.parts.reserve(parts.second.parts.size());
789 for (std::pair<std::string, int> &p : parts.second.parts) {
790 new_parts.parts.emplace_back(std::move(p.first));
791 }
792 new_file.parts.emplace_back(std::move(new_parts));
Austin Schuh5212cad2020-09-09 23:12:09 -0700793 }
Austin Schuh11d43732020-09-21 17:28:30 -0700794 result.emplace_back(std::move(new_file));
795 }
796 return result;
797}
798
799std::ostream &operator<<(std::ostream &stream, const LogFile &file) {
800 stream << "{";
Brian Silvermanae7c0332020-09-30 16:58:23 -0700801 if (!file.log_event_uuid.empty()) {
802 stream << "\"log_event_uuid\": \"" << file.log_event_uuid << "\", ";
Austin Schuh11d43732020-09-21 17:28:30 -0700803 }
804 stream << "\"parts\": [";
805 for (size_t i = 0; i < file.parts.size(); ++i) {
806 if (i != 0u) {
807 stream << ", ";
808 }
809 stream << file.parts[i];
810 }
811 stream << "]}";
812 return stream;
813}
814std::ostream &operator<<(std::ostream &stream, const LogParts &parts) {
815 stream << "{";
Brian Silvermanae7c0332020-09-30 16:58:23 -0700816 if (!parts.log_event_uuid.empty()) {
817 stream << "\"log_event_uuid\": \"" << parts.log_event_uuid << "\", ";
Austin Schuh11d43732020-09-21 17:28:30 -0700818 }
819 if (!parts.parts_uuid.empty()) {
820 stream << "\"parts_uuid\": \"" << parts.parts_uuid << "\", ";
821 }
822 if (!parts.node.empty()) {
823 stream << "\"node\": \"" << parts.node << "\", ";
824 }
825 stream << "\"monotonic_start_time\": " << parts.monotonic_start_time
826 << ", \"realtime_start_time\": " << parts.realtime_start_time << ", [";
827
828 for (size_t i = 0; i < parts.parts.size(); ++i) {
829 if (i != 0u) {
830 stream << ", ";
831 }
832 stream << parts.parts[i];
833 }
834
835 stream << "]}";
836 return stream;
837}
838
839std::vector<std::vector<std::string>> ToLogReaderVector(
840 const std::vector<LogFile> &log_files) {
841 std::vector<std::vector<std::string>> result;
842 for (const LogFile &log_file : log_files) {
843 for (const LogParts &log_parts : log_file.parts) {
844 std::vector<std::string> parts;
845 for (const std::string &part : log_parts.parts) {
846 parts.emplace_back(part);
847 }
848 result.emplace_back(std::move(parts));
849 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700850 }
851 return result;
852}
853
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800854LogReader::LogReader(std::string_view filename,
855 const Configuration *replay_configuration)
Austin Schuhfa895892020-01-07 20:07:41 -0800856 : LogReader(std::vector<std::string>{std::string(filename)},
857 replay_configuration) {}
858
859LogReader::LogReader(const std::vector<std::string> &filenames,
860 const Configuration *replay_configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800861 : LogReader(std::vector<std::vector<std::string>>{filenames},
862 replay_configuration) {}
863
Austin Schuh11d43732020-09-21 17:28:30 -0700864// TODO(austin): Make this the base and kill the others. This has much better
865// context for sorting.
866LogReader::LogReader(const std::vector<LogFile> &log_files,
867 const Configuration *replay_configuration)
868 : LogReader(ToLogReaderVector(log_files), replay_configuration) {}
869
Austin Schuh6f3babe2020-01-26 20:34:50 -0800870LogReader::LogReader(const std::vector<std::vector<std::string>> &filenames,
871 const Configuration *replay_configuration)
872 : filenames_(filenames),
873 log_file_header_(ReadHeader(filenames[0][0])),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800874 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800875 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800876
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700877 // Remap all existing remote timestamp channels. They will be recreated, and
878 // the data logged isn't relevant anymore.
879 for (const Node *node : Nodes()) {
880 std::vector<const Node *> timestamp_logger_nodes =
881 configuration::TimestampNodes(logged_configuration(), node);
882 for (const Node *remote_node : timestamp_logger_nodes) {
883 const std::string channel = absl::StrCat(
884 "/aos/remote_timestamps/", remote_node->name()->string_view());
885 CHECK(HasChannel<logger::MessageHeader>(channel, node))
886 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
887 << logger::MessageHeader::GetFullyQualifiedName() << "\"} for node "
888 << node->name()->string_view();
889 RemapLoggedChannel<logger::MessageHeader>(channel, node);
890 }
891 }
892
Austin Schuh6aa77be2020-02-22 21:06:40 -0800893 if (replay_configuration) {
894 CHECK_EQ(configuration::MultiNode(configuration()),
895 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700896 << ": Log file and replay config need to both be multi or single "
897 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800898 }
899
Austin Schuh6f3babe2020-01-26 20:34:50 -0800900 if (!configuration::MultiNode(configuration())) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700901 states_.emplace_back(
902 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800903 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800904 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700905 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800906 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700907 << ": Log file and replay config need to have matching nodes "
908 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700909 for (const Node *node : *logged_configuration()->nodes()) {
910 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700911 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
912 << " in logged config that is not present in the replay "
913 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700914 }
915 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800916 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800917 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800918 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800919}
920
Austin Schuh6aa77be2020-02-22 21:06:40 -0800921LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700922 if (event_loop_factory_unique_ptr_) {
923 Deregister();
924 } else if (event_loop_factory_ != nullptr) {
925 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
926 "is destroyed";
927 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800928 if (offset_fp_ != nullptr) {
929 fclose(offset_fp_);
930 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700931 // Zero out some buffers. It's easy to do use-after-frees on these, so make
932 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700933 if (remapped_configuration_buffer_) {
934 remapped_configuration_buffer_->Wipe();
935 }
936 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -0800937}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800938
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800939const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800940 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800941}
942
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800943const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800944 return remapped_configuration_;
945}
946
Austin Schuh6f3babe2020-01-26 20:34:50 -0800947std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700948 // Because the Node pointer will only be valid if it actually points to
949 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800950 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800951 //
952 // Also, note, that when ever a map is changed, the nodes in here are
953 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800954 CHECK(remapped_configuration_ != nullptr)
955 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800956 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800957}
Austin Schuh15649d62019-12-28 16:36:38 -0800958
Austin Schuh11d43732020-09-21 17:28:30 -0700959monotonic_clock::time_point LogReader::monotonic_start_time(
960 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800961 State *state =
962 states_[configuration::GetNodeIndex(configuration(), node)].get();
963 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
964
Austin Schuh858c9f32020-08-31 16:56:12 -0700965 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800966}
967
Austin Schuh11d43732020-09-21 17:28:30 -0700968realtime_clock::time_point LogReader::realtime_start_time(
969 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800970 State *state =
971 states_[configuration::GetNodeIndex(configuration(), node)].get();
972 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
973
Austin Schuh858c9f32020-08-31 16:56:12 -0700974 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800975}
976
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800977void LogReader::Register() {
978 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800979 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800980 Register(event_loop_factory_unique_ptr_.get());
981}
982
Austin Schuh92547522019-12-28 14:33:43 -0800983void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800984 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700985 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -0800986
Brian Silvermand90905f2020-09-23 14:42:56 -0700987 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800988 const size_t node_index =
989 configuration::GetNodeIndex(configuration(), node);
Austin Schuh858c9f32020-08-31 16:56:12 -0700990 states_[node_index] =
991 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames_));
Austin Schuh8bd96322020-02-13 21:18:22 -0800992 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700993 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -0700994 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700995
996 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -0800997 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700998
999 // Register after making all the State objects so we can build references
1000 // between them.
1001 for (const Node *node : configuration::GetNodes(configuration())) {
1002 const size_t node_index =
1003 configuration::GetNodeIndex(configuration(), node);
1004 State *state = states_[node_index].get();
1005
1006 Register(state->event_loop());
1007 }
1008
James Kuszmaul46d82582020-05-09 19:50:09 -07001009 if (live_nodes_ == 0) {
1010 LOG(FATAL)
1011 << "Don't have logs from any of the nodes in the replay config--are "
1012 "you sure that the replay config matches the original config?";
1013 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001014
Austin Schuh2f8fd752020-09-01 22:38:28 -07001015 // We need to now seed our per-node time offsets and get everything set up
1016 // to run.
1017 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -08001018
Austin Schuh8bd96322020-02-13 21:18:22 -08001019 // It is easiest to solve for per node offsets with a matrix rather than
1020 // trying to solve the equations by hand. So let's get after it.
1021 //
1022 // Now, build up the map matrix.
1023 //
Austin Schuh2f8fd752020-09-01 22:38:28 -07001024 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
1025 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1026 filters_.size() + 1, num_nodes);
1027 slope_matrix_ =
1028 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
1029 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -08001030
Austin Schuh2f8fd752020-09-01 22:38:28 -07001031 offset_matrix_ =
1032 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1033 valid_matrix_ =
1034 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
1035 last_valid_matrix_ =
1036 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -08001037
Austin Schuh2f8fd752020-09-01 22:38:28 -07001038 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
1039 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -08001040
Austin Schuh2f8fd752020-09-01 22:38:28 -07001041 // All times should average out to the distributed clock.
1042 for (int i = 0; i < map_matrix_.cols(); ++i) {
1043 // 1/num_nodes.
1044 map_matrix_(0, i) = mpq_class(1, num_nodes);
1045 }
1046 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -08001047
1048 {
1049 // Now, add the a - b -> sample elements.
1050 size_t i = 1;
1051 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001052 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1053 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001054 const Node *const node_a = std::get<0>(filter.first);
1055 const Node *const node_b = std::get<1>(filter.first);
1056
1057 const size_t node_a_index =
1058 configuration::GetNodeIndex(configuration(), node_a);
1059 const size_t node_b_index =
1060 configuration::GetNodeIndex(configuration(), node_b);
1061
Austin Schuh2f8fd752020-09-01 22:38:28 -07001062 // -a
1063 map_matrix_(i, node_a_index) = mpq_class(-1);
1064 // +b
1065 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -08001066
1067 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -07001068 std::get<0>(filter.second)
1069 .set_slope_pointer(&slope_matrix_(i, node_a_index));
1070 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
1071
1072 valid_matrix_(i) = false;
1073 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -08001074
1075 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001076 }
1077 }
1078
Austin Schuh858c9f32020-08-31 16:56:12 -07001079 for (std::unique_ptr<State> &state : states_) {
1080 state->SeedSortedMessages();
1081 }
1082
Austin Schuh2f8fd752020-09-01 22:38:28 -07001083 // Rank of the map matrix tells you if all the nodes are in communication
1084 // with each other, which tells you if the offsets are observable.
1085 const size_t connected_nodes =
1086 Eigen::FullPivLU<
1087 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
1088 .rank();
1089
1090 // We don't need to support isolated nodes until someone has a real use
1091 // case.
1092 CHECK_EQ(connected_nodes, num_nodes)
1093 << ": There is a node which isn't communicating with the rest.";
1094
1095 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001096 UpdateOffsets();
1097
Austin Schuh2f8fd752020-09-01 22:38:28 -07001098 // We want to start the log file at the last start time of the log files
1099 // from all the nodes. Compute how long each node's simulation needs to run
1100 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001101 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001102
Austin Schuh2f8fd752020-09-01 22:38:28 -07001103 // TODO(austin): We want an "OnStart" callback for each node rather than
1104 // running until the last node.
1105
Austin Schuh8bd96322020-02-13 21:18:22 -08001106 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001107 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1108 << MaybeNodeName(state->event_loop()->node()) << "now "
1109 << state->monotonic_now();
1110 // And start computing the start time on the distributed clock now that
1111 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001112 start_time = std::max(
1113 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001114 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001115
1116 CHECK_GE(start_time, distributed_clock::epoch())
1117 << ": Hmm, we have a node starting before the start of time. Offset "
1118 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001119
Austin Schuh6f3babe2020-01-26 20:34:50 -08001120 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1121 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001122 // nodes, and also replayed on the other nodes. This may not satisfy all
1123 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001124 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1125 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1126 const Channel *channel = logged_configuration()->channels()->Get(i);
1127 const Node *node = configuration::GetNode(
1128 configuration(), channel->source_node()->string_view());
1129
Austin Schuh8bd96322020-02-13 21:18:22 -08001130 State *state =
1131 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001132
1133 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001134 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001135
1136 event_loop_factory_->DisableForwarding(remapped_channel);
1137 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001138
1139 // If we are replaying a log, we don't want a bunch of redundant messages
1140 // from both the real message bridge and simulated message bridge.
1141 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001142 }
1143
Austin Schuhcde938c2020-02-02 17:30:07 -08001144 // While we are starting the system up, we might be relying on matching data
1145 // to timestamps on log files where the timestamp log file starts before the
1146 // data. In this case, it is reasonable to expect missing data.
1147 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001148 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001149 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001150 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001151 // Now that we are running for real, missing data means that the log file is
1152 // corrupted or went wrong.
1153 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001154
Austin Schuh8bd96322020-02-13 21:18:22 -08001155 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001156 // Make the RT clock be correct before handing it to the user.
1157 if (state->realtime_start_time() != realtime_clock::min_time) {
1158 state->SetRealtimeOffset(state->monotonic_start_time(),
1159 state->realtime_start_time());
1160 }
1161 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1162 << MaybeNodeName(state->event_loop()->node()) << "now "
1163 << state->monotonic_now();
1164 }
1165
1166 if (FLAGS_timestamps_to_csv) {
1167 for (std::pair<const std::tuple<const Node *, const Node *>,
1168 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1169 &filter : filters_) {
1170 const Node *const node_a = std::get<0>(filter.first);
1171 const Node *const node_b = std::get<1>(filter.first);
1172
1173 std::get<0>(filter.second)
1174 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1175 ->monotonic_now());
1176 std::get<0>(filter.second)
1177 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1178 ->monotonic_now());
1179 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001180 }
1181}
1182
Austin Schuh2f8fd752020-09-01 22:38:28 -07001183void LogReader::UpdateOffsets() {
1184 VLOG(2) << "Samples are " << offset_matrix_;
1185 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1186 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1187 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1188 "]");
1189 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1190 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1191
1192 size_t node_index = 0;
1193 for (std::unique_ptr<State> &state : states_) {
1194 state->SetDistributedOffset(offset(node_index), slope(node_index));
1195 VLOG(1) << "Offset for node " << node_index << " "
1196 << MaybeNodeName(state->event_loop()->node()) << "is "
1197 << aos::distributed_clock::time_point(offset(node_index))
1198 << " slope " << std::setprecision(9) << std::fixed
1199 << slope(node_index);
1200 ++node_index;
1201 }
1202
1203 if (VLOG_IS_ON(1)) {
1204 LogFit("Offset is");
1205 }
1206}
1207
1208void LogReader::LogFit(std::string_view prefix) {
1209 for (std::unique_ptr<State> &state : states_) {
1210 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1211 << state->monotonic_now() << " distributed "
1212 << event_loop_factory_->distributed_now();
1213 }
1214
1215 for (std::pair<const std::tuple<const Node *, const Node *>,
1216 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1217 filters_) {
1218 message_bridge::NoncausalOffsetEstimator *estimator =
1219 &std::get<0>(filter.second);
1220
1221 if (estimator->a_timestamps().size() == 0 &&
1222 estimator->b_timestamps().size() == 0) {
1223 continue;
1224 }
1225
1226 if (VLOG_IS_ON(1)) {
1227 estimator->LogFit(prefix);
1228 }
1229
1230 const Node *const node_a = std::get<0>(filter.first);
1231 const Node *const node_b = std::get<1>(filter.first);
1232
1233 const size_t node_a_index =
1234 configuration::GetNodeIndex(configuration(), node_a);
1235 const size_t node_b_index =
1236 configuration::GetNodeIndex(configuration(), node_b);
1237
1238 const double recovered_slope =
1239 slope(node_b_index) / slope(node_a_index) - 1.0;
1240 const int64_t recovered_offset =
1241 offset(node_b_index).count() - offset(node_a_index).count() *
1242 slope(node_b_index) /
1243 slope(node_a_index);
1244
1245 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1246 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1247 << " offset " << std::setprecision(20) << recovered_offset
1248 << " (error "
1249 << recovered_offset - estimator->fit().offset().count() << ")";
1250
1251 const aos::distributed_clock::time_point a0 =
1252 states_[node_a_index]->ToDistributedClock(
1253 std::get<0>(estimator->a_timestamps()[0]));
1254 const aos::distributed_clock::time_point a1 =
1255 states_[node_a_index]->ToDistributedClock(
1256 std::get<0>(estimator->a_timestamps()[1]));
1257
1258 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1259 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1260 << " distributed -> " << node_b->name()->string_view() << " "
1261 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1262 << aos::monotonic_clock::time_point(
1263 std::chrono::nanoseconds(static_cast<int64_t>(
1264 std::get<0>(estimator->a_timestamps()[0])
1265 .time_since_epoch()
1266 .count() *
1267 (1.0 + estimator->fit().slope()))) +
1268 estimator->fit().offset())
1269 << ((a0 <= event_loop_factory_->distributed_now())
1270 ? ""
1271 : " After now, investigate");
1272 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1273 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1274 << " distributed -> " << node_b->name()->string_view() << " "
1275 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1276 << aos::monotonic_clock::time_point(
1277 std::chrono::nanoseconds(static_cast<int64_t>(
1278 std::get<0>(estimator->a_timestamps()[1])
1279 .time_since_epoch()
1280 .count() *
1281 (1.0 + estimator->fit().slope()))) +
1282 estimator->fit().offset())
1283 << ((event_loop_factory_->distributed_now() <= a1)
1284 ? ""
1285 : " Before now, investigate");
1286
1287 const aos::distributed_clock::time_point b0 =
1288 states_[node_b_index]->ToDistributedClock(
1289 std::get<0>(estimator->b_timestamps()[0]));
1290 const aos::distributed_clock::time_point b1 =
1291 states_[node_b_index]->ToDistributedClock(
1292 std::get<0>(estimator->b_timestamps()[1]));
1293
1294 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1295 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1296 << " distributed -> " << node_a->name()->string_view() << " "
1297 << states_[node_a_index]->FromDistributedClock(b0)
1298 << ((b0 <= event_loop_factory_->distributed_now())
1299 ? ""
1300 : " After now, investigate");
1301 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1302 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1303 << " distributed -> " << node_a->name()->string_view() << " "
1304 << states_[node_a_index]->FromDistributedClock(b1)
1305 << ((event_loop_factory_->distributed_now() <= b1)
1306 ? ""
1307 : " Before now, investigate");
1308 }
1309}
1310
1311message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001312 const Node *node_a, const Node *node_b) {
1313 CHECK_NE(node_a, node_b);
1314 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1315 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1316
1317 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001318 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001319 }
1320
1321 auto tuple = std::make_tuple(node_a, node_b);
1322
1323 auto it = filters_.find(tuple);
1324
1325 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001326 auto &x =
1327 filters_
1328 .insert(std::make_pair(
1329 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1330 node_a, node_b))))
1331 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001332 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001333 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1334 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1335 node_b->name()->string_view()));
1336 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1337 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1338 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001339 }
1340
Austin Schuh2f8fd752020-09-01 22:38:28 -07001341 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001342 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001343 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001344 }
1345}
1346
Austin Schuhe309d2a2019-11-29 13:25:21 -08001347void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001348 State *state =
1349 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1350 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001351
Austin Schuh858c9f32020-08-31 16:56:12 -07001352 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001353
Tyler Chatow67ddb032020-01-12 14:30:04 -08001354 // We don't run timing reports when trying to print out logged data, because
1355 // otherwise we would end up printing out the timing reports themselves...
1356 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001357 event_loop->SkipTimingReport();
1358 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001359
Austin Schuh858c9f32020-08-31 16:56:12 -07001360 const bool has_data = state->SetNode();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001361
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001362 for (size_t logged_channel_index = 0;
1363 logged_channel_index < logged_configuration()->channels()->size();
1364 ++logged_channel_index) {
1365 const Channel *channel = RemapChannel(
1366 event_loop,
1367 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001368
Austin Schuh2f8fd752020-09-01 22:38:28 -07001369 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001370 aos::Sender<MessageHeader> *remote_timestamp_sender = nullptr;
1371
1372 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001373
1374 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1375 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001376 // We've got a message which is being forwarded to this node.
1377 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001378 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001379 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001380
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001381 // Delivery timestamps are supposed to be logged back on the source node.
1382 // Configure remote timestamps to be sent.
1383 const bool delivery_time_is_logged =
1384 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1385 channel, event_loop->node(), source_node);
1386
1387 source_state =
1388 states_[configuration::GetNodeIndex(configuration(), source_node)]
1389 .get();
1390
1391 if (delivery_time_is_logged) {
1392 remote_timestamp_sender =
1393 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001394 }
1395 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001396
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001397 state->SetChannel(
1398 logged_channel_index,
1399 configuration::ChannelIndex(event_loop->configuration(), channel),
1400 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1401 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001402 }
1403
Austin Schuh6aa77be2020-02-22 21:06:40 -08001404 // If we didn't find any log files with data in them, we won't ever get a
1405 // callback or be live. So skip the rest of the setup.
1406 if (!has_data) {
1407 return;
1408 }
1409
Austin Schuh858c9f32020-08-31 16:56:12 -07001410 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001411 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1412 << "at " << state->event_loop()->context().monotonic_event_time
1413 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001414 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001415 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001416 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001417 if (live_nodes_ == 0) {
1418 event_loop_factory_->Exit();
1419 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001420 return;
1421 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001422 TimestampMerger::DeliveryTimestamp channel_timestamp;
Austin Schuh05b70472020-01-01 17:11:17 -08001423 int channel_index;
1424 FlatbufferVector<MessageHeader> channel_data =
1425 FlatbufferVector<MessageHeader>::Empty();
1426
Austin Schuh2f8fd752020-09-01 22:38:28 -07001427 if (VLOG_IS_ON(1)) {
1428 LogFit("Offset was");
1429 }
1430
1431 bool update_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001432 std::tie(channel_timestamp, channel_index, channel_data) =
Austin Schuh2f8fd752020-09-01 22:38:28 -07001433 state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001434
Austin Schuhe309d2a2019-11-29 13:25:21 -08001435 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001436 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001437 if (!FLAGS_skip_order_validation) {
1438 CHECK(monotonic_now == channel_timestamp.monotonic_event_time)
1439 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1440 << monotonic_now << " trying to send "
1441 << channel_timestamp.monotonic_event_time << " failure "
1442 << state->DebugString();
1443 } else if (monotonic_now != channel_timestamp.monotonic_event_time) {
1444 LOG(WARNING) << "Check failed: monotonic_now == "
1445 "channel_timestamp.monotonic_event_time) ("
1446 << monotonic_now << " vs. "
1447 << channel_timestamp.monotonic_event_time
1448 << "): " << FlatbufferToJson(state->event_loop()->node())
1449 << " Now " << monotonic_now << " trying to send "
1450 << channel_timestamp.monotonic_event_time << " failure "
1451 << state->DebugString();
1452 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001453
Austin Schuh6f3babe2020-01-26 20:34:50 -08001454 if (channel_timestamp.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001455 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001456 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001457 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001458 !state->at_end()) ||
Austin Schuh05b70472020-01-01 17:11:17 -08001459 channel_data.message().data() != nullptr) {
1460 CHECK(channel_data.message().data() != nullptr)
1461 << ": Got a message without data. Forwarding entry which was "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001462 "not matched? Use --skip_missing_forwarding_entries to "
Brian Silverman87ac0402020-09-17 14:47:01 -07001463 "ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001464
Austin Schuh2f8fd752020-09-01 22:38:28 -07001465 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001466 // Confirm that the message was sent on the sending node before the
1467 // destination node (this node). As a proxy, do this by making sure
1468 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001469 if (!FLAGS_skip_order_validation) {
1470 CHECK_LT(channel_timestamp.monotonic_remote_time,
1471 state->monotonic_remote_now(channel_index))
1472 << state->event_loop()->node()->name()->string_view() << " to "
1473 << state->remote_node(channel_index)->name()->string_view()
1474 << " " << state->DebugString();
1475 } else if (channel_timestamp.monotonic_remote_time >=
1476 state->monotonic_remote_now(channel_index)) {
1477 LOG(WARNING)
1478 << "Check failed: channel_timestamp.monotonic_remote_time < "
1479 "state->monotonic_remote_now(channel_index) ("
1480 << channel_timestamp.monotonic_remote_time << " vs. "
1481 << state->monotonic_remote_now(channel_index) << ") "
1482 << state->event_loop()->node()->name()->string_view() << " to "
1483 << state->remote_node(channel_index)->name()->string_view()
1484 << " currently " << channel_timestamp.monotonic_event_time
1485 << " ("
1486 << state->ToDistributedClock(
1487 channel_timestamp.monotonic_event_time)
1488 << ") remote event time "
1489 << channel_timestamp.monotonic_remote_time << " ("
1490 << state->RemoteToDistributedClock(
1491 channel_index, channel_timestamp.monotonic_remote_time)
1492 << ") " << state->DebugString();
1493 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001494
1495 if (FLAGS_timestamps_to_csv) {
1496 if (offset_fp_ == nullptr) {
1497 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1498 fprintf(
1499 offset_fp_,
1500 "# time_since_start, offset node 0, offset node 1, ...\n");
1501 first_time_ = channel_timestamp.realtime_event_time;
1502 }
1503
1504 fprintf(offset_fp_, "%.9f",
1505 std::chrono::duration_cast<std::chrono::duration<double>>(
1506 channel_timestamp.realtime_event_time - first_time_)
1507 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001508 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1509 fprintf(offset_fp_, ", %.9f",
1510 time_offset_matrix_(i, 0) +
1511 time_slope_matrix_(i, 0) *
1512 chrono::duration<double>(
1513 event_loop_factory_->distributed_now()
1514 .time_since_epoch())
1515 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001516 }
1517 fprintf(offset_fp_, "\n");
1518 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001519 }
1520
Austin Schuh15649d62019-12-28 16:36:38 -08001521 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh858c9f32020-08-31 16:56:12 -07001522 state->SetRealtimeOffset(channel_timestamp.monotonic_event_time,
1523 channel_timestamp.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001524
Austin Schuh2f8fd752020-09-01 22:38:28 -07001525 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
1526 << channel_timestamp.monotonic_event_time;
1527 // TODO(austin): std::move channel_data in and make that efficient in
1528 // simulation.
Austin Schuh858c9f32020-08-31 16:56:12 -07001529 state->Send(channel_index, channel_data.message().data()->Data(),
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001530 channel_data.message().data()->size(), channel_timestamp);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001531 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001532 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001533 // reading the rest of the log file and call it quits. We don't want
1534 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001535 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1536 bool update_time_dummy;
1537 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001538 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001539 } else {
1540 CHECK(channel_data.message().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001541 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001542 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001543 LOG(WARNING)
1544 << "Not sending data from before the start of the log file. "
1545 << channel_timestamp.monotonic_event_time.time_since_epoch().count()
1546 << " start " << monotonic_start_time().time_since_epoch().count()
1547 << " " << FlatbufferToJson(channel_data);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001548 }
1549
Austin Schuh858c9f32020-08-31 16:56:12 -07001550 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001551 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001552 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1553 << "wakeup for " << next_time << "("
1554 << state->ToDistributedClock(next_time)
1555 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001556 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001557 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001558 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1559 << "No next message, scheduling shutdown";
1560 // Set a timer up immediately after now to die. If we don't do this,
1561 // then the senders waiting on the message we just read will never get
1562 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001563 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001564 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1565 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001566 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001567 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001568
Austin Schuh2f8fd752020-09-01 22:38:28 -07001569 // Once we make this call, the current time changes. So do everything
1570 // which involves time before changing it. That especially includes
1571 // sending the message.
1572 if (update_time) {
1573 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1574 << "updating offsets";
1575
1576 std::vector<aos::monotonic_clock::time_point> before_times;
1577 before_times.resize(states_.size());
1578 std::transform(states_.begin(), states_.end(), before_times.begin(),
1579 [](const std::unique_ptr<State> &state) {
1580 return state->monotonic_now();
1581 });
1582
1583 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001584 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1585 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001586 }
1587
Austin Schuh8bd96322020-02-13 21:18:22 -08001588 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001589 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1590 << state->monotonic_now();
1591
1592 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001593 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1594 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001595 }
1596
1597 // TODO(austin): We should be perfect.
1598 const std::chrono::nanoseconds kTolerance{3};
1599 if (!FLAGS_skip_order_validation) {
1600 CHECK_GE(next_time, state->monotonic_now())
1601 << ": Time skipped the next event.";
1602
1603 for (size_t i = 0; i < states_.size(); ++i) {
1604 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1605 << ": Time changed too much on node "
1606 << MaybeNodeName(states_[i]->event_loop()->node());
1607 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1608 << ": Time changed too much on node "
1609 << states_[i]->event_loop()->node()->name()->string_view();
1610 }
1611 } else {
1612 if (next_time < state->monotonic_now()) {
1613 LOG(WARNING) << "Check failed: next_time >= "
1614 "state->monotonic_now() ("
1615 << next_time << " vs. " << state->monotonic_now()
1616 << "): Time skipped the next event.";
1617 }
1618 for (size_t i = 0; i < states_.size(); ++i) {
1619 if (states_[i]->monotonic_now() >= before_times[i] - kTolerance) {
1620 LOG(WARNING) << "Check failed: "
1621 "states_[i]->monotonic_now() "
1622 ">= before_times[i] - kTolerance ("
1623 << states_[i]->monotonic_now() << " vs. "
1624 << before_times[i] - kTolerance
1625 << ") : Time changed too much on node "
1626 << MaybeNodeName(states_[i]->event_loop()->node());
1627 }
1628 if (states_[i]->monotonic_now() <= before_times[i] + kTolerance) {
1629 LOG(WARNING) << "Check failed: "
1630 "states_[i]->monotonic_now() "
1631 "<= before_times[i] + kTolerance ("
1632 << states_[i]->monotonic_now() << " vs. "
1633 << before_times[i] - kTolerance
1634 << ") : Time changed too much on node "
1635 << MaybeNodeName(states_[i]->event_loop()->node());
1636 }
1637 }
1638 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001639 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001640
1641 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1642 << state->event_loop()->context().monotonic_event_time << " now "
1643 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001644 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001645
Austin Schuh6f3babe2020-01-26 20:34:50 -08001646 ++live_nodes_;
1647
Austin Schuh858c9f32020-08-31 16:56:12 -07001648 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1649 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001650 }
1651}
1652
1653void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001654 // Make sure that things get destroyed in the correct order, rather than
1655 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001656 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001657 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001658 }
Austin Schuh92547522019-12-28 14:33:43 -08001659
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001660 event_loop_factory_unique_ptr_.reset();
1661 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001662}
1663
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001664void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1665 std::string_view add_prefix) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001666 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1667 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1668 if (channel->name()->str() == name &&
1669 channel->type()->string_view() == type) {
1670 CHECK_EQ(0u, remapped_channels_.count(ii))
1671 << "Already remapped channel "
1672 << configuration::CleanedChannelToString(channel);
1673 remapped_channels_[ii] = std::string(add_prefix) + std::string(name);
1674 VLOG(1) << "Remapping channel "
1675 << configuration::CleanedChannelToString(channel)
1676 << " to have name " << remapped_channels_[ii];
Austin Schuh6331ef92020-01-07 18:28:09 -08001677 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001678 return;
1679 }
1680 }
1681 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1682 << type;
1683}
1684
Austin Schuh01b4c352020-09-21 23:09:39 -07001685void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1686 const Node *node,
1687 std::string_view add_prefix) {
1688 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1689 const Channel *remapped_channel =
1690 configuration::GetChannel(logged_configuration(), name, type, "", node);
1691 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1692 << "\", \"type\": \"" << type << "\"}";
1693 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1694 << "\"}";
1695 VLOG(1) << "Remapped "
1696 << aos::configuration::StrippedChannelToString(remapped_channel);
1697
1698 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1699 // we want it to degrade if the heuristics fail to just work.
1700 //
1701 // The easiest way to do this is going to be incredibly specific and verbose.
1702 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1703 // /original/0/spray. Then, create a map from /original/spray to
1704 // /original/0/spray for just the type we were asked for.
1705 if (name != remapped_channel->name()->string_view()) {
1706 MapT new_map;
1707 new_map.match = std::make_unique<ChannelT>();
1708 new_map.match->name = absl::StrCat(add_prefix, name);
1709 new_map.match->type = type;
1710 if (node != nullptr) {
1711 new_map.match->source_node = node->name()->str();
1712 }
1713 new_map.rename = std::make_unique<ChannelT>();
1714 new_map.rename->name =
1715 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1716 maps_.emplace_back(std::move(new_map));
1717 }
1718
1719 const size_t channel_index =
1720 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1721 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1722 << "Already remapped channel "
1723 << configuration::CleanedChannelToString(remapped_channel);
1724 remapped_channels_[channel_index] =
1725 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1726 MakeRemappedConfig();
1727}
1728
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001729void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001730 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001731 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001732 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001733 << ": Can't change the mapping after the events are scheduled.";
1734 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001735 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001736
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001737 // If no remapping occurred and we are using the original config, then there
1738 // is nothing interesting to do here.
1739 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001740 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001741 return;
1742 }
1743 // Config to copy Channel definitions from. Use the specified
1744 // replay_configuration_ if it has been provided.
1745 const Configuration *const base_config = replay_configuration_ == nullptr
1746 ? logged_configuration()
1747 : replay_configuration_;
1748 // The remapped config will be identical to the base_config, except that it
1749 // will have a bunch of extra channels in the channel list, which are exact
1750 // copies of the remapped channels, but with different names.
1751 // Because the flatbuffers API is a pain to work with, this requires a bit of
1752 // a song-and-dance to get copied over.
1753 // The order of operations is to:
1754 // 1) Make a flatbuffer builder for a config that will just contain a list of
1755 // the new channels that we want to add.
1756 // 2) For each channel that we are remapping:
1757 // a) Make a buffer/builder and construct into it a Channel table that only
1758 // contains the new name for the channel.
1759 // b) Merge the new channel with just the name into the channel that we are
1760 // trying to copy, built in the flatbuffer builder made in 1. This gives
1761 // us the new channel definition that we need.
1762 // 3) Using this list of offsets, build the Configuration of just new
1763 // Channels.
1764 // 4) Merge the Configuration with the new Channels into the base_config.
1765 // 5) Call MergeConfiguration() on that result to give MergeConfiguration a
1766 // chance to sanitize the config.
1767
1768 // This is the builder that we use for the config containing all the new
1769 // channels.
1770 flatbuffers::FlatBufferBuilder new_config_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001771 new_config_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001772 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
1773 for (auto &pair : remapped_channels_) {
1774 // This is the builder that we use for creating the Channel with just the
1775 // new name.
1776 flatbuffers::FlatBufferBuilder new_name_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001777 new_name_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001778 const flatbuffers::Offset<flatbuffers::String> name_offset =
1779 new_name_fbb.CreateString(pair.second);
1780 ChannelBuilder new_name_builder(new_name_fbb);
1781 new_name_builder.add_name(name_offset);
1782 new_name_fbb.Finish(new_name_builder.Finish());
1783 const FlatbufferDetachedBuffer<Channel> new_name = new_name_fbb.Release();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001784 // Retrieve the channel that we want to copy, confirming that it is
1785 // actually present in base_config.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001786 const Channel *const base_channel = CHECK_NOTNULL(configuration::GetChannel(
1787 base_config, logged_configuration()->channels()->Get(pair.first), "",
1788 nullptr));
1789 // Actually create the new channel and put it into the vector of Offsets
1790 // that we will use to create the new Configuration.
1791 channel_offsets.emplace_back(MergeFlatBuffers<Channel>(
1792 reinterpret_cast<const flatbuffers::Table *>(base_channel),
1793 reinterpret_cast<const flatbuffers::Table *>(&new_name.message()),
1794 &new_config_fbb));
1795 }
1796 // Create the Configuration containing the new channels that we want to add.
Austin Schuh01b4c352020-09-21 23:09:39 -07001797 const auto new_channel_vector_offsets =
Austin Schuhfa895892020-01-07 20:07:41 -08001798 new_config_fbb.CreateVector(channel_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001799
1800 // Now create the new maps.
1801 std::vector<flatbuffers::Offset<Map>> map_offsets;
1802 for (const MapT &map : maps_) {
1803 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
1804 new_config_fbb.CreateString(map.match->name);
1805 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
1806 new_config_fbb.CreateString(map.match->type);
1807 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1808 new_config_fbb.CreateString(map.rename->name);
1809 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1810 if (!map.match->source_node.empty()) {
1811 match_source_node_offset =
1812 new_config_fbb.CreateString(map.match->source_node);
1813 }
1814 Channel::Builder match_builder(new_config_fbb);
1815 match_builder.add_name(match_name_offset);
1816 match_builder.add_type(match_type_offset);
1817 if (!map.match->source_node.empty()) {
1818 match_builder.add_source_node(match_source_node_offset);
1819 }
1820 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1821
1822 Channel::Builder rename_builder(new_config_fbb);
1823 rename_builder.add_name(rename_name_offset);
1824 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1825
1826 Map::Builder map_builder(new_config_fbb);
1827 map_builder.add_match(match_offset);
1828 map_builder.add_rename(rename_offset);
1829 map_offsets.emplace_back(map_builder.Finish());
1830 }
1831
1832 const auto new_maps_offsets = new_config_fbb.CreateVector(map_offsets);
1833
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001834 ConfigurationBuilder new_config_builder(new_config_fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001835 new_config_builder.add_channels(new_channel_vector_offsets);
1836 new_config_builder.add_maps(new_maps_offsets);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001837 new_config_fbb.Finish(new_config_builder.Finish());
1838 const FlatbufferDetachedBuffer<Configuration> new_name_config =
1839 new_config_fbb.Release();
1840 // Merge the new channels configuration into the base_config, giving us the
1841 // remapped configuration.
1842 remapped_configuration_buffer_ =
1843 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1844 MergeFlatBuffers<Configuration>(base_config,
1845 &new_name_config.message()));
1846 // Call MergeConfiguration to deal with sanitizing the config.
1847 remapped_configuration_buffer_ =
1848 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1849 configuration::MergeConfiguration(*remapped_configuration_buffer_));
1850
1851 remapped_configuration_ = &remapped_configuration_buffer_->message();
1852}
1853
Austin Schuh6f3babe2020-01-26 20:34:50 -08001854const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1855 const Channel *channel) {
1856 std::string_view channel_name = channel->name()->string_view();
1857 std::string_view channel_type = channel->type()->string_view();
1858 const int channel_index =
1859 configuration::ChannelIndex(logged_configuration(), channel);
1860 // If the channel is remapped, find the correct channel name to use.
1861 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001862 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001863 << configuration::CleanedChannelToString(channel);
1864 channel_name = remapped_channels_[channel_index];
1865 }
1866
Austin Schuhee711052020-08-24 16:06:09 -07001867 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001868 const Channel *remapped_channel = configuration::GetChannel(
1869 event_loop->configuration(), channel_name, channel_type,
1870 event_loop->name(), event_loop->node());
1871
1872 CHECK(remapped_channel != nullptr)
1873 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1874 << channel_type << "\"} because it is not in the provided configuration.";
1875
1876 return remapped_channel;
1877}
1878
Austin Schuh858c9f32020-08-31 16:56:12 -07001879LogReader::State::State(std::unique_ptr<ChannelMerger> channel_merger)
1880 : channel_merger_(std::move(channel_merger)) {}
1881
1882EventLoop *LogReader::State::SetNodeEventLoopFactory(
1883 NodeEventLoopFactory *node_event_loop_factory) {
1884 node_event_loop_factory_ = node_event_loop_factory;
1885 event_loop_unique_ptr_ =
1886 node_event_loop_factory_->MakeEventLoop("log_reader");
1887 return event_loop_unique_ptr_.get();
1888}
1889
1890void LogReader::State::SetChannelCount(size_t count) {
1891 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001892 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001893 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001894 channel_source_state_.resize(count);
1895 factory_channel_index_.resize(count);
1896 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001897}
1898
1899void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001900 size_t logged_channel_index, size_t factory_channel_index,
1901 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001902 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001903 aos::Sender<MessageHeader> *remote_timestamp_sender, State *source_state) {
1904 channels_[logged_channel_index] = std::move(sender);
1905 filters_[logged_channel_index] = filter;
1906 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1907
1908 if (source_state) {
1909 channel_source_state_[logged_channel_index] = source_state;
1910
1911 if (remote_timestamp_sender != nullptr) {
1912 source_state->queue_index_map_[logged_channel_index] =
1913 std::make_unique<std::vector<State::SentTimestamp>>();
1914 }
1915 }
1916
1917 factory_channel_index_[logged_channel_index] = factory_channel_index;
1918}
1919
1920bool LogReader::State::Send(
1921 size_t channel_index, const void *data, size_t size,
1922 const TimestampMerger::DeliveryTimestamp &delivery_timestamp) {
1923 aos::RawSender *sender = channels_[channel_index].get();
1924 uint32_t remote_queue_index = 0xffffffff;
1925
1926 if (remote_timestamp_senders_[channel_index] != nullptr) {
1927 std::vector<SentTimestamp> *queue_index_map =
1928 CHECK_NOTNULL(CHECK_NOTNULL(channel_source_state_[channel_index])
1929 ->queue_index_map_[channel_index]
1930 .get());
1931
1932 SentTimestamp search;
1933 search.monotonic_event_time = delivery_timestamp.monotonic_remote_time;
1934 search.realtime_event_time = delivery_timestamp.realtime_remote_time;
1935 search.queue_index = delivery_timestamp.remote_queue_index;
1936
1937 // Find the sent time if available.
1938 auto element = std::lower_bound(
1939 queue_index_map->begin(), queue_index_map->end(), search,
1940 [](SentTimestamp a, SentTimestamp b) {
1941 if (b.monotonic_event_time < a.monotonic_event_time) {
1942 return false;
1943 }
1944 if (b.monotonic_event_time > a.monotonic_event_time) {
1945 return true;
1946 }
1947
1948 if (b.queue_index < a.queue_index) {
1949 return false;
1950 }
1951 if (b.queue_index > a.queue_index) {
1952 return true;
1953 }
1954
1955 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1956 return false;
1957 });
1958
1959 // TODO(austin): Be a bit more principled here, but we will want to do that
1960 // after the logger rewrite. We hit this when one node finishes, but the
1961 // other node isn't done yet. So there is no send time, but there is a
1962 // receive time.
1963 if (element != queue_index_map->end()) {
1964 CHECK_EQ(element->monotonic_event_time,
1965 delivery_timestamp.monotonic_remote_time);
1966 CHECK_EQ(element->realtime_event_time,
1967 delivery_timestamp.realtime_remote_time);
1968 CHECK_EQ(element->queue_index, delivery_timestamp.remote_queue_index);
1969
1970 remote_queue_index = element->actual_queue_index;
1971 }
1972 }
1973
1974 // Send! Use the replayed queue index here instead of the logged queue index
1975 // for the remote queue index. This makes re-logging work.
1976 const bool sent =
1977 sender->Send(data, size, delivery_timestamp.monotonic_remote_time,
1978 delivery_timestamp.realtime_remote_time, remote_queue_index);
1979 if (!sent) return false;
1980
1981 if (queue_index_map_[channel_index]) {
1982 SentTimestamp timestamp;
1983 timestamp.monotonic_event_time = delivery_timestamp.monotonic_event_time;
1984 timestamp.realtime_event_time = delivery_timestamp.realtime_event_time;
1985 timestamp.queue_index = delivery_timestamp.queue_index;
1986 timestamp.actual_queue_index = sender->sent_queue_index();
1987 queue_index_map_[channel_index]->emplace_back(timestamp);
1988 } else if (remote_timestamp_senders_[channel_index] != nullptr) {
1989 aos::Sender<MessageHeader>::Builder builder =
1990 remote_timestamp_senders_[channel_index]->MakeBuilder();
1991
1992 logger::MessageHeader::Builder message_header_builder =
1993 builder.MakeBuilder<logger::MessageHeader>();
1994
1995 message_header_builder.add_channel_index(
1996 factory_channel_index_[channel_index]);
1997
1998 // Swap the remote and sent metrics. They are from the sender's
1999 // perspective, not the receiver's perspective.
2000 message_header_builder.add_monotonic_sent_time(
2001 sender->monotonic_sent_time().time_since_epoch().count());
2002 message_header_builder.add_realtime_sent_time(
2003 sender->realtime_sent_time().time_since_epoch().count());
2004 message_header_builder.add_queue_index(sender->sent_queue_index());
2005
2006 message_header_builder.add_monotonic_remote_time(
2007 delivery_timestamp.monotonic_remote_time.time_since_epoch().count());
2008 message_header_builder.add_realtime_remote_time(
2009 delivery_timestamp.realtime_remote_time.time_since_epoch().count());
2010
2011 message_header_builder.add_remote_queue_index(remote_queue_index);
2012
2013 builder.Send(message_header_builder.Finish());
2014 }
2015
2016 return true;
2017}
2018
2019aos::Sender<MessageHeader> *LogReader::State::RemoteTimestampSender(
2020 const Node *delivered_node) {
2021 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2022
2023 if (sender == remote_timestamp_senders_map_.end()) {
2024 sender = remote_timestamp_senders_map_
2025 .emplace(std::make_pair(
2026 delivered_node,
2027 event_loop()->MakeSender<MessageHeader>(
2028 absl::StrCat("/aos/remote_timestamps/",
2029 delivered_node->name()->string_view()))))
2030 .first;
2031 }
2032
2033 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07002034}
2035
2036std::tuple<TimestampMerger::DeliveryTimestamp, int,
2037 FlatbufferVector<MessageHeader>>
2038LogReader::State::PopOldest(bool *update_time) {
2039 CHECK_GT(sorted_messages_.size(), 0u);
2040
2041 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -07002042 FlatbufferVector<MessageHeader>,
2043 message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002044 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002045 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002046 << std::get<0>(result).monotonic_event_time;
2047 sorted_messages_.pop_front();
2048 SeedSortedMessages();
2049
Austin Schuh2f8fd752020-09-01 22:38:28 -07002050 if (std::get<3>(result) != nullptr) {
2051 *update_time = std::get<3>(result)->Pop(
2052 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2053 } else {
2054 *update_time = false;
2055 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002056 return std::make_tuple(std::get<0>(result), std::get<1>(result),
2057 std::move(std::get<2>(result)));
2058}
2059
2060monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2061 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002062 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002063 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2064 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2065 }
2066
2067 return channel_merger_->OldestMessageTime();
2068}
2069
2070void LogReader::State::SeedSortedMessages() {
2071 const aos::monotonic_clock::time_point end_queue_time =
2072 (sorted_messages_.size() > 0
2073 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
2074 : channel_merger_->monotonic_start_time()) +
2075 std::chrono::seconds(2);
2076
2077 while (true) {
2078 if (channel_merger_->OldestMessageTime() == monotonic_clock::max_time) {
2079 return;
2080 }
2081 if (sorted_messages_.size() > 0) {
2082 // Stop placing sorted messages on the list once we have 2 seconds
2083 // queued up (but queue at least until the log starts.
2084 if (end_queue_time <
2085 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2086 return;
2087 }
2088 }
2089
2090 TimestampMerger::DeliveryTimestamp channel_timestamp;
2091 int channel_index;
2092 FlatbufferVector<MessageHeader> channel_data =
2093 FlatbufferVector<MessageHeader>::Empty();
2094
Austin Schuh2f8fd752020-09-01 22:38:28 -07002095 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2096
Austin Schuh858c9f32020-08-31 16:56:12 -07002097 std::tie(channel_timestamp, channel_index, channel_data) =
2098 channel_merger_->PopOldest();
2099
Austin Schuh2f8fd752020-09-01 22:38:28 -07002100 // Skip any messages without forwarding information.
2101 if (channel_timestamp.monotonic_remote_time != monotonic_clock::min_time) {
2102 // Got a forwarding timestamp!
2103 filter = filters_[channel_index];
2104
2105 CHECK(filter != nullptr);
2106
2107 // Call the correct method depending on if we are the forward or
2108 // reverse direction here.
2109 filter->Sample(event_loop_->node(),
2110 channel_timestamp.monotonic_event_time,
2111 channel_timestamp.monotonic_remote_time);
2112 }
Austin Schuh858c9f32020-08-31 16:56:12 -07002113 sorted_messages_.emplace_back(channel_timestamp, channel_index,
Austin Schuh2f8fd752020-09-01 22:38:28 -07002114 std::move(channel_data), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002115 }
2116}
2117
2118void LogReader::State::Deregister() {
2119 for (size_t i = 0; i < channels_.size(); ++i) {
2120 channels_[i].reset();
2121 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002122 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002123 event_loop_unique_ptr_.reset();
2124 event_loop_ = nullptr;
2125 timer_handler_ = nullptr;
2126 node_event_loop_factory_ = nullptr;
2127}
2128
Austin Schuhe309d2a2019-11-29 13:25:21 -08002129} // namespace logger
2130} // namespace aos