blob: 57d6909398649e8329691f15e0b96110698c6a6d [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
55 // Find all the nodes which are logging timestamps on our node.
56 std::set<const Node *> timestamp_logger_nodes;
Austin Schuh0c297012020-09-16 18:41:59 -070057 for (const Channel *channel : *configuration_->channels()) {
Brian Silverman1f345222020-09-24 21:14:48 -070058 if (!configuration::ChannelIsSendableOnNode(channel, event_loop_->node())) {
59 continue;
60 }
61 if (!channel->has_destination_nodes()) {
62 continue;
63 }
64 if (!should_log(channel)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070065 continue;
66 }
67 for (const Connection *connection : *channel->destination_nodes()) {
68 const Node *other_node = configuration::GetNode(
Austin Schuh0c297012020-09-16 18:41:59 -070069 configuration_, connection->name()->string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -070070
71 if (configuration::ConnectionDeliveryTimeIsLoggedOnNode(
72 connection, event_loop_->node())) {
73 VLOG(1) << "Timestamps are logged from "
74 << FlatbufferToJson(other_node);
75 timestamp_logger_nodes.insert(other_node);
76 }
77 }
78 }
79
80 std::map<const Channel *, const Node *> timestamp_logger_channels;
81
82 // Now that we have all the nodes accumulated, make remote timestamp loggers
83 // for them.
84 for (const Node *node : timestamp_logger_nodes) {
85 const Channel *channel = configuration::GetChannel(
Austin Schuh0c297012020-09-16 18:41:59 -070086 configuration_,
Austin Schuh2f8fd752020-09-01 22:38:28 -070087 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
88 logger::MessageHeader::GetFullyQualifiedName(), event_loop_->name(),
89 event_loop_->node());
90
91 CHECK(channel != nullptr)
92 << ": Remote timestamps are logged on "
93 << event_loop_->node()->name()->string_view()
94 << " but can't find channel /aos/remote_timestamps/"
95 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -070096 if (!should_log(channel)) {
97 continue;
98 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070099 timestamp_logger_channels.insert(std::make_pair(channel, node));
100 }
101
Brian Silvermand90905f2020-09-23 14:42:56 -0700102 const size_t our_node_index =
103 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700104
Brian Silverman1f345222020-09-24 21:14:48 -0700105 for (size_t channel_index = 0;
106 channel_index < configuration_->channels()->size(); ++channel_index) {
107 const Channel *const config_channel =
108 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700109 // The MakeRawFetcher method needs a channel which is in the event loop
110 // configuration() object, not the configuration_ object. Go look that up
111 // from the config.
112 const Channel *channel = aos::configuration::GetChannel(
113 event_loop_->configuration(), config_channel->name()->string_view(),
114 config_channel->type()->string_view(), "", event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700115 if (!should_log(channel)) {
116 continue;
117 }
Austin Schuh0c297012020-09-16 18:41:59 -0700118
Austin Schuhe309d2a2019-11-29 13:25:21 -0800119 FetcherStruct fs;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700120 fs.node_index = our_node_index;
Brian Silverman1f345222020-09-24 21:14:48 -0700121 fs.channel_index = channel_index;
122 fs.channel = channel;
123
Austin Schuh6f3babe2020-01-26 20:34:50 -0800124 const bool is_local =
125 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
126
Austin Schuh15649d62019-12-28 16:36:38 -0800127 const bool is_readable =
128 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700129 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
130 channel, event_loop_->node());
131 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800132
Brian Silverman1f345222020-09-24 21:14:48 -0700133 bool log_delivery_times = false;
134 if (event_loop_->node() != nullptr) {
135 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
136 channel, event_loop_->node(), event_loop_->node());
137 }
Austin Schuh15649d62019-12-28 16:36:38 -0800138
Austin Schuh2f8fd752020-09-01 22:38:28 -0700139 // Now, detect a MessageHeader timestamp logger where we should just log the
140 // contents to a file directly.
141 const bool log_contents = timestamp_logger_channels.find(channel) !=
142 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700143
144 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800145 fs.fetcher = event_loop->MakeRawFetcher(channel);
146 VLOG(1) << "Logging channel "
147 << configuration::CleanedChannelToString(channel);
148
149 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800150 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700151 fs.wants_timestamp_writer = true;
Austin Schuh15649d62019-12-28 16:36:38 -0800152 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800153 if (log_message) {
154 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700155 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800156 if (!is_local) {
157 fs.log_type = LogType::kLogRemoteMessage;
158 }
159 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700160 if (log_contents) {
161 VLOG(1) << "Timestamp logger channel "
162 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700163 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
164 fs.wants_contents_writer = true;
Austin Schuh0c297012020-09-16 18:41:59 -0700165 fs.node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700166 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700167 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800168 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800169 }
Brian Silverman1f345222020-09-24 21:14:48 -0700170 }
171}
172
173Logger::~Logger() {
174 if (log_namer_) {
175 // If we are replaying a log file, or in simulation, we want to force the
176 // last bit of data to be logged. The easiest way to deal with this is to
177 // poll everything as we go to destroy the class, ie, shut down the logger,
178 // and write it to disk.
179 StopLogging(event_loop_->monotonic_now());
180 }
181}
182
Brian Silvermanae7c0332020-09-30 16:58:23 -0700183void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
184 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700185 CHECK(!log_namer_) << ": Already logging";
186 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700187 log_event_uuid_ = UUID::Random();
188 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700189 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
190
191 // We want to do as much work as possible before the initial Fetch. Time
192 // between that and actually starting to log opens up the possibility of
193 // falling off the end of the queue during that time.
194
195 for (FetcherStruct &f : fetchers_) {
196 if (f.wants_writer) {
197 f.writer = log_namer_->MakeWriter(f.channel);
198 }
199 if (f.wants_timestamp_writer) {
200 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
201 }
202 if (f.wants_contents_writer) {
203 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
204 f.channel, CHECK_NOTNULL(f.timestamp_node));
205 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800206 }
207
Brian Silverman1f345222020-09-24 21:14:48 -0700208 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700209 node_state_.resize(configuration::MultiNode(configuration_)
210 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700211 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800212
Austin Schuh2f8fd752020-09-01 22:38:28 -0700213 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700214 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800215
Austin Schuh2f8fd752020-09-01 22:38:28 -0700216 node_state_[node_index].log_file_header = MakeHeader(node);
217 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800218
Austin Schuh2f8fd752020-09-01 22:38:28 -0700219 // Grab data from each channel right before we declare the log file started
220 // so we can capture the latest message on each channel. This lets us have
221 // non periodic messages with configuration that now get logged.
222 for (FetcherStruct &f : fetchers_) {
223 f.written = !f.fetcher->Fetch();
224 }
225
226 // Clear out any old timestamps in case we are re-starting logging.
227 for (size_t i = 0; i < node_state_.size(); ++i) {
228 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time);
229 }
230
231 WriteHeader();
232
233 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
234 << " start_time " << last_synchronized_time_;
235
236 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
237 polling_period_);
238}
239
Brian Silverman1f345222020-09-24 21:14:48 -0700240std::unique_ptr<LogNamer> Logger::StopLogging(
241 aos::monotonic_clock::time_point end_time) {
242 CHECK(log_namer_) << ": Not logging right now";
243
244 if (end_time != aos::monotonic_clock::min_time) {
245 LogUntil(end_time);
246 }
247 timer_handler_->Disable();
248
249 for (FetcherStruct &f : fetchers_) {
250 f.writer = nullptr;
251 f.timestamp_writer = nullptr;
252 f.contents_writer = nullptr;
253 }
254 node_state_.clear();
255
Brian Silvermanae7c0332020-09-30 16:58:23 -0700256 log_event_uuid_ = UUID::Zero();
257 log_start_uuid_ = std::string();
258
Brian Silverman1f345222020-09-24 21:14:48 -0700259 return std::move(log_namer_);
260}
261
Austin Schuhfa895892020-01-07 20:07:41 -0800262void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700263 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700264 server_statistics_fetcher_.Fetch();
265 }
266
267 aos::monotonic_clock::time_point monotonic_start_time =
268 event_loop_->monotonic_now();
269 aos::realtime_clock::time_point realtime_start_time =
270 event_loop_->realtime_now();
271
272 // We need to pick a point in time to declare the log file "started". This
273 // starts here. It needs to be after everything is fetched so that the
274 // fetchers are all pointed at the most recent message before the start
275 // time.
276 last_synchronized_time_ = monotonic_start_time;
277
Austin Schuh6f3babe2020-01-26 20:34:50 -0800278 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700279 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700280 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
281 realtime_start_time);
Austin Schuh64fab802020-09-09 22:47:47 -0700282 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800283 }
284}
Austin Schuh8bd96322020-02-13 21:18:22 -0800285
Austin Schuh2f8fd752020-09-01 22:38:28 -0700286void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700287 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700288 server_statistics_fetcher_.Fetch();
289 } else {
290 return;
291 }
292
293 if (server_statistics_fetcher_.get() == nullptr) {
294 return;
295 }
296
297 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700298 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700299 if (MaybeUpdateTimestamp(
300 node, node_index,
301 server_statistics_fetcher_.context().monotonic_event_time,
302 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh64fab802020-09-09 22:47:47 -0700303 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700304 }
305 }
306}
307
308void Logger::SetStartTime(size_t node_index,
309 aos::monotonic_clock::time_point monotonic_start_time,
310 aos::realtime_clock::time_point realtime_start_time) {
311 node_state_[node_index].monotonic_start_time = monotonic_start_time;
312 node_state_[node_index].realtime_start_time = realtime_start_time;
313 node_state_[node_index]
314 .log_file_header.mutable_message()
315 ->mutate_monotonic_start_time(
316 std::chrono::duration_cast<std::chrono::nanoseconds>(
317 monotonic_start_time.time_since_epoch())
318 .count());
319 if (node_state_[node_index]
320 .log_file_header.mutable_message()
321 ->has_realtime_start_time()) {
322 node_state_[node_index]
323 .log_file_header.mutable_message()
324 ->mutate_realtime_start_time(
325 std::chrono::duration_cast<std::chrono::nanoseconds>(
326 realtime_start_time.time_since_epoch())
327 .count());
328 }
329}
330
331bool Logger::MaybeUpdateTimestamp(
332 const Node *node, int node_index,
333 aos::monotonic_clock::time_point monotonic_start_time,
334 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700335 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700336 if (node_state_[node_index].monotonic_start_time !=
337 monotonic_clock::min_time) {
338 return false;
339 }
Austin Schuh0c297012020-09-16 18:41:59 -0700340 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700341 if (event_loop_->node() == node) {
342 // There are no offsets to compute for ourself, so always succeed.
343 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
344 return true;
345 } else if (server_statistics_fetcher_.get() != nullptr) {
346 // We must be a remote node now. Look for the connection and see if it is
347 // connected.
348
349 for (const message_bridge::ServerConnection *connection :
350 *server_statistics_fetcher_->connections()) {
351 if (connection->node()->name()->string_view() !=
352 node->name()->string_view()) {
353 continue;
354 }
355
356 if (connection->state() != message_bridge::State::CONNECTED) {
357 VLOG(1) << node->name()->string_view()
358 << " is not connected, can't start it yet.";
359 break;
360 }
361
362 if (!connection->has_monotonic_offset()) {
363 VLOG(1) << "Missing monotonic offset for setting start time for node "
364 << aos::FlatbufferToJson(node);
365 break;
366 }
367
368 VLOG(1) << "Updating start time for " << aos::FlatbufferToJson(node);
369
370 // Found it and it is connected. Compensate and go.
371 monotonic_start_time +=
372 std::chrono::nanoseconds(connection->monotonic_offset());
373
374 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
375 return true;
376 }
377 }
378 } else {
379 SetStartTime(node_index, monotonic_start_time, realtime_start_time);
380 return true;
381 }
382 return false;
383}
384
385aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
386 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800387 // Now write the header with this timestamp in it.
388 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800389 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800390
Austin Schuh2f8fd752020-09-01 22:38:28 -0700391 // TODO(austin): Compress this much more efficiently. There are a bunch of
392 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700393 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700394 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800395
Brian Silvermanae7c0332020-09-30 16:58:23 -0700396 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700397 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800398
Brian Silvermanae7c0332020-09-30 16:58:23 -0700399 CHECK(log_event_uuid_ != UUID::Zero());
400 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
401 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700402
Brian Silvermanae7c0332020-09-30 16:58:23 -0700403 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
404 fbb.CreateString(logger_instance_uuid_.string_view());
405
406 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
407 if (!log_start_uuid_.empty()) {
408 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
409 }
410
411 const flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
412 fbb.CreateString(boot_uuid_);
413
414 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700415 fbb.CreateString("00000000-0000-4000-8000-000000000000");
416
Austin Schuhfa895892020-01-07 20:07:41 -0800417 flatbuffers::Offset<Node> node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700418
Austin Schuh0c297012020-09-16 18:41:59 -0700419 if (configuration::MultiNode(configuration_)) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800420 node_offset = CopyFlatBuffer(node, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800421 }
422
423 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
424
Austin Schuh64fab802020-09-09 22:47:47 -0700425 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800426
427 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800428 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800429 log_file_header_builder.add_node(node_offset);
430 }
431
432 log_file_header_builder.add_configuration(configuration_offset);
433 // The worst case theoretical out of order is the polling period times 2.
434 // One message could get logged right after the boundary, but be for right
435 // before the next boundary. And the reverse could happen for another
436 // message. Report back 3x to be extra safe, and because the cost isn't
437 // huge on the read side.
438 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700439 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800440
441 log_file_header_builder.add_monotonic_start_time(
442 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700443 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800444 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700445 if (node == event_loop_->node()) {
446 log_file_header_builder.add_realtime_start_time(
447 std::chrono::duration_cast<std::chrono::nanoseconds>(
448 realtime_clock::min_time.time_since_epoch())
449 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800450 }
451
Brian Silvermanae7c0332020-09-30 16:58:23 -0700452 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
453 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
454 if (!log_start_uuid_offset.IsNull()) {
455 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
456 }
457 log_file_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700458
459 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
460 log_file_header_builder.add_parts_index(0);
461
Austin Schuh2f8fd752020-09-01 22:38:28 -0700462 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
463 return fbb.Release();
464}
465
466void Logger::Rotate() {
467 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700468 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700469 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700470 }
471}
472
473void Logger::LogUntil(monotonic_clock::time_point t) {
474 WriteMissingTimestamps();
475
476 // Write each channel to disk, one at a time.
477 for (FetcherStruct &f : fetchers_) {
478 while (true) {
479 if (f.written) {
480 if (!f.fetcher->FetchNext()) {
481 VLOG(2) << "No new data on "
482 << configuration::CleanedChannelToString(
483 f.fetcher->channel());
484 break;
485 } else {
486 f.written = false;
487 }
488 }
489
490 CHECK(!f.written);
491
492 // TODO(james): Write tests to exercise this logic.
493 if (f.fetcher->context().monotonic_event_time < t) {
494 if (f.writer != nullptr) {
495 // Write!
496 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
497 max_header_size_);
498 fbb.ForceDefaults(true);
499
500 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
501 f.channel_index, f.log_type));
502
503 VLOG(2) << "Writing data as node "
504 << FlatbufferToJson(event_loop_->node()) << " for channel "
505 << configuration::CleanedChannelToString(f.fetcher->channel())
506 << " to " << f.writer->filename() << " data "
507 << FlatbufferToJson(
508 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
509 fbb.GetBufferPointer()));
510
511 max_header_size_ = std::max(
512 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
513 f.writer->QueueSizedFlatbuffer(&fbb);
514 }
515
516 if (f.timestamp_writer != nullptr) {
517 // And now handle timestamps.
518 flatbuffers::FlatBufferBuilder fbb;
519 fbb.ForceDefaults(true);
520
521 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
522 f.channel_index,
523 LogType::kLogDeliveryTimeOnly));
524
525 VLOG(2) << "Writing timestamps as node "
526 << FlatbufferToJson(event_loop_->node()) << " for channel "
527 << configuration::CleanedChannelToString(f.fetcher->channel())
528 << " to " << f.timestamp_writer->filename() << " timestamp "
529 << FlatbufferToJson(
530 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
531 fbb.GetBufferPointer()));
532
533 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
534 }
535
536 if (f.contents_writer != nullptr) {
537 // And now handle the special message contents channel. Copy the
538 // message into a FlatBufferBuilder and save it to disk.
539 // TODO(austin): We can be more efficient here when we start to
540 // care...
541 flatbuffers::FlatBufferBuilder fbb;
542 fbb.ForceDefaults(true);
543
544 const MessageHeader *msg =
545 flatbuffers::GetRoot<MessageHeader>(f.fetcher->context().data);
546
547 logger::MessageHeader::Builder message_header_builder(fbb);
548
549 // Note: this must match the same order as MessageBridgeServer and
550 // PackMessage. We want identical headers to have identical
551 // on-the-wire formats to make comparing them easier.
552 message_header_builder.add_channel_index(msg->channel_index());
553
554 message_header_builder.add_queue_index(msg->queue_index());
555 message_header_builder.add_monotonic_sent_time(
556 msg->monotonic_sent_time());
557 message_header_builder.add_realtime_sent_time(
558 msg->realtime_sent_time());
559
560 message_header_builder.add_monotonic_remote_time(
561 msg->monotonic_remote_time());
562 message_header_builder.add_realtime_remote_time(
563 msg->realtime_remote_time());
564 message_header_builder.add_remote_queue_index(
565 msg->remote_queue_index());
566
567 fbb.FinishSizePrefixed(message_header_builder.Finish());
568
569 f.contents_writer->QueueSizedFlatbuffer(&fbb);
570 }
571
572 f.written = true;
573 } else {
574 break;
575 }
576 }
577 }
578 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800579}
580
Brian Silverman1f345222020-09-24 21:14:48 -0700581void Logger::DoLogData(const monotonic_clock::time_point end_time) {
582 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800583 // max_out_of_order_duration. To do this, we need sync points. Every write
584 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800585
586 do {
587 // Move the sync point up by at most polling_period. This forces one sync
588 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700589 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
590
591 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800592
Austin Schuhe309d2a2019-11-29 13:25:21 -0800593 // If we missed cycles, we could be pretty far behind. Spin until we are
594 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700595 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800596}
597
Austin Schuh11d43732020-09-21 17:28:30 -0700598std::vector<LogFile> SortParts(const std::vector<std::string> &parts) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700599 // Start by grouping all parts by UUID, and extracting the part index.
Austin Schuh11d43732020-09-21 17:28:30 -0700600 // Datastructure to hold all the info extracted from a set of parts which go
601 // together so we can sort them afterwords.
602 struct UnsortedLogParts {
603 // Start times.
604 aos::monotonic_clock::time_point monotonic_start_time;
605 aos::realtime_clock::time_point realtime_start_time;
606
607 // Node to save.
608 std::string node;
609
610 // Pairs of the filename and the part index for sorting.
611 std::vector<std::pair<std::string, int>> parts;
612 };
613
Brian Silvermanae7c0332020-09-30 16:58:23 -0700614 // Map holding the log_event_uuid -> second map. The second map holds the
Austin Schuh11d43732020-09-21 17:28:30 -0700615 // parts_uuid -> list of parts for sorting.
616 std::map<std::string, std::map<std::string, UnsortedLogParts>> parts_list;
Austin Schuh5212cad2020-09-09 23:12:09 -0700617
618 // Sort part files without UUIDs and part indexes as well. Extract everything
619 // useful from the log in the first pass, then sort later.
Austin Schuh11d43732020-09-21 17:28:30 -0700620 struct UnsortedOldParts {
621 // Part information with everything but the list of parts.
622 LogParts parts;
623
624 // Tuple of time for the data and filename needed for sorting after
625 // extracting.
Brian Silvermand90905f2020-09-23 14:42:56 -0700626 std::vector<std::pair<monotonic_clock::time_point, std::string>>
627 unsorted_parts;
Austin Schuh5212cad2020-09-09 23:12:09 -0700628 };
629
Austin Schuh11d43732020-09-21 17:28:30 -0700630 // A list of all the old parts which we don't know how to sort using uuids.
631 // There are enough of these in the wild that this is worth supporting.
632 std::vector<UnsortedOldParts> old_parts;
Austin Schuh5212cad2020-09-09 23:12:09 -0700633
Austin Schuh11d43732020-09-21 17:28:30 -0700634 // Now extract everything into our datastructures above for sorting.
Austin Schuh5212cad2020-09-09 23:12:09 -0700635 for (const std::string &part : parts) {
636 FlatbufferVector<LogFileHeader> log_header = ReadHeader(part);
637
Austin Schuh11d43732020-09-21 17:28:30 -0700638 const monotonic_clock::time_point monotonic_start_time(
639 chrono::nanoseconds(log_header.message().monotonic_start_time()));
640 const realtime_clock::time_point realtime_start_time(
641 chrono::nanoseconds(log_header.message().realtime_start_time()));
642
643 const std::string_view node =
644 log_header.message().has_node()
645 ? log_header.message().node()->name()->string_view()
646 : "";
647
Austin Schuh5212cad2020-09-09 23:12:09 -0700648 // Looks like an old log. No UUID, index, and also single node. We have
649 // little to no multi-node log files in the wild without part UUIDs and
650 // indexes which we care much about.
651 if (!log_header.message().has_parts_uuid() &&
652 !log_header.message().has_parts_index() &&
653 !log_header.message().has_node()) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700654 FlatbufferVector<MessageHeader> first_message = ReadNthMessage(part, 0);
Austin Schuh11d43732020-09-21 17:28:30 -0700655 const monotonic_clock::time_point first_message_time(
Austin Schuh5212cad2020-09-09 23:12:09 -0700656 chrono::nanoseconds(first_message.message().monotonic_sent_time()));
Austin Schuh11d43732020-09-21 17:28:30 -0700657
658 // Find anything with a matching start time. They all go together.
659 auto result = std::find_if(
660 old_parts.begin(), old_parts.end(),
661 [&](const UnsortedOldParts &parts) {
662 return parts.parts.monotonic_start_time == monotonic_start_time &&
663 parts.parts.realtime_start_time == realtime_start_time;
664 });
665
666 if (result == old_parts.end()) {
667 old_parts.emplace_back();
668 old_parts.back().parts.monotonic_start_time = monotonic_start_time;
669 old_parts.back().parts.realtime_start_time = realtime_start_time;
670 old_parts.back().unsorted_parts.emplace_back(
671 std::make_pair(first_message_time, part));
672 } else {
673 result->unsorted_parts.emplace_back(
674 std::make_pair(first_message_time, part));
675 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700676 continue;
677 }
678
Brian Silvermanae7c0332020-09-30 16:58:23 -0700679 CHECK(log_header.message().has_log_event_uuid());
Austin Schuh5212cad2020-09-09 23:12:09 -0700680 CHECK(log_header.message().has_parts_uuid());
681 CHECK(log_header.message().has_parts_index());
682
Brian Silvermanae7c0332020-09-30 16:58:23 -0700683 const std::string log_event_uuid =
684 log_header.message().log_event_uuid()->str();
Austin Schuh5212cad2020-09-09 23:12:09 -0700685 const std::string parts_uuid = log_header.message().parts_uuid()->str();
Austin Schuh11d43732020-09-21 17:28:30 -0700686 int32_t parts_index = log_header.message().parts_index();
687
Brian Silvermanae7c0332020-09-30 16:58:23 -0700688 auto log_it = parts_list.find(log_event_uuid);
Austin Schuh11d43732020-09-21 17:28:30 -0700689 if (log_it == parts_list.end()) {
Brian Silvermanae7c0332020-09-30 16:58:23 -0700690 log_it =
691 parts_list
692 .insert(std::make_pair(log_event_uuid,
693 std::map<std::string, UnsortedLogParts>()))
694 .first;
Austin Schuh5212cad2020-09-09 23:12:09 -0700695 }
Austin Schuh11d43732020-09-21 17:28:30 -0700696
697 auto it = log_it->second.find(parts_uuid);
698 if (it == log_it->second.end()) {
699 it = log_it->second.insert(std::make_pair(parts_uuid, UnsortedLogParts()))
700 .first;
701 it->second.monotonic_start_time = monotonic_start_time;
702 it->second.realtime_start_time = realtime_start_time;
703 it->second.node = std::string(node);
704 }
705
706 // First part might be min_time. If it is, try to put a better time on it.
707 if (it->second.monotonic_start_time == monotonic_clock::min_time) {
708 it->second.monotonic_start_time = monotonic_start_time;
709 } else if (monotonic_start_time != monotonic_clock::min_time) {
710 CHECK_EQ(it->second.monotonic_start_time, monotonic_start_time);
711 }
712 if (it->second.realtime_start_time == realtime_clock::min_time) {
713 it->second.realtime_start_time = realtime_start_time;
714 } else if (realtime_start_time != realtime_clock::min_time) {
715 CHECK_EQ(it->second.realtime_start_time, realtime_start_time);
716 }
717
718 it->second.parts.emplace_back(std::make_pair(part, parts_index));
Austin Schuh5212cad2020-09-09 23:12:09 -0700719 }
720
721 CHECK_NE(old_parts.empty(), parts_list.empty())
722 << ": Can't have a mix of old and new parts.";
723
Austin Schuh11d43732020-09-21 17:28:30 -0700724 // Now reformat old_parts to be in the right datastructure to report.
Austin Schuh5212cad2020-09-09 23:12:09 -0700725 if (!old_parts.empty()) {
Austin Schuh11d43732020-09-21 17:28:30 -0700726 std::vector<LogFile> result;
727 for (UnsortedOldParts &p : old_parts) {
728 // Sort by the oldest message in each file.
729 std::sort(
730 p.unsorted_parts.begin(), p.unsorted_parts.end(),
731 [](const std::pair<monotonic_clock::time_point, std::string> &a,
732 const std::pair<monotonic_clock::time_point, std::string> &b) {
733 return a.first < b.first;
734 });
735 LogFile log_file;
736 for (std::pair<monotonic_clock::time_point, std::string> &f :
737 p.unsorted_parts) {
738 p.parts.parts.emplace_back(std::move(f.second));
739 }
740 log_file.parts.emplace_back(std::move(p.parts));
741 result.emplace_back(std::move(log_file));
Austin Schuh5212cad2020-09-09 23:12:09 -0700742 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700743
Austin Schuh11d43732020-09-21 17:28:30 -0700744 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700745 }
746
747 // Now, sort them and produce the final vector form.
Austin Schuh11d43732020-09-21 17:28:30 -0700748 std::vector<LogFile> result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700749 result.reserve(parts_list.size());
Brian Silvermand90905f2020-09-23 14:42:56 -0700750 for (std::pair<const std::string, std::map<std::string, UnsortedLogParts>>
751 &logs : parts_list) {
Austin Schuh11d43732020-09-21 17:28:30 -0700752 LogFile new_file;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700753 new_file.log_event_uuid = logs.first;
Austin Schuh11d43732020-09-21 17:28:30 -0700754 for (std::pair<const std::string, UnsortedLogParts> &parts : logs.second) {
755 LogParts new_parts;
756 new_parts.monotonic_start_time = parts.second.monotonic_start_time;
757 new_parts.realtime_start_time = parts.second.realtime_start_time;
Brian Silvermanae7c0332020-09-30 16:58:23 -0700758 new_parts.log_event_uuid = logs.first;
Austin Schuh11d43732020-09-21 17:28:30 -0700759 new_parts.parts_uuid = parts.first;
760 new_parts.node = std::move(parts.second.node);
761
762 std::sort(parts.second.parts.begin(), parts.second.parts.end(),
763 [](const std::pair<std::string, int> &a,
764 const std::pair<std::string, int> &b) {
765 return a.second < b.second;
766 });
767 new_parts.parts.reserve(parts.second.parts.size());
768 for (std::pair<std::string, int> &p : parts.second.parts) {
769 new_parts.parts.emplace_back(std::move(p.first));
770 }
771 new_file.parts.emplace_back(std::move(new_parts));
Austin Schuh5212cad2020-09-09 23:12:09 -0700772 }
Austin Schuh11d43732020-09-21 17:28:30 -0700773 result.emplace_back(std::move(new_file));
774 }
775 return result;
776}
777
778std::ostream &operator<<(std::ostream &stream, const LogFile &file) {
779 stream << "{";
Brian Silvermanae7c0332020-09-30 16:58:23 -0700780 if (!file.log_event_uuid.empty()) {
781 stream << "\"log_event_uuid\": \"" << file.log_event_uuid << "\", ";
Austin Schuh11d43732020-09-21 17:28:30 -0700782 }
783 stream << "\"parts\": [";
784 for (size_t i = 0; i < file.parts.size(); ++i) {
785 if (i != 0u) {
786 stream << ", ";
787 }
788 stream << file.parts[i];
789 }
790 stream << "]}";
791 return stream;
792}
793std::ostream &operator<<(std::ostream &stream, const LogParts &parts) {
794 stream << "{";
Brian Silvermanae7c0332020-09-30 16:58:23 -0700795 if (!parts.log_event_uuid.empty()) {
796 stream << "\"log_event_uuid\": \"" << parts.log_event_uuid << "\", ";
Austin Schuh11d43732020-09-21 17:28:30 -0700797 }
798 if (!parts.parts_uuid.empty()) {
799 stream << "\"parts_uuid\": \"" << parts.parts_uuid << "\", ";
800 }
801 if (!parts.node.empty()) {
802 stream << "\"node\": \"" << parts.node << "\", ";
803 }
804 stream << "\"monotonic_start_time\": " << parts.monotonic_start_time
805 << ", \"realtime_start_time\": " << parts.realtime_start_time << ", [";
806
807 for (size_t i = 0; i < parts.parts.size(); ++i) {
808 if (i != 0u) {
809 stream << ", ";
810 }
811 stream << parts.parts[i];
812 }
813
814 stream << "]}";
815 return stream;
816}
817
818std::vector<std::vector<std::string>> ToLogReaderVector(
819 const std::vector<LogFile> &log_files) {
820 std::vector<std::vector<std::string>> result;
821 for (const LogFile &log_file : log_files) {
822 for (const LogParts &log_parts : log_file.parts) {
823 std::vector<std::string> parts;
824 for (const std::string &part : log_parts.parts) {
825 parts.emplace_back(part);
826 }
827 result.emplace_back(std::move(parts));
828 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700829 }
830 return result;
831}
832
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800833LogReader::LogReader(std::string_view filename,
834 const Configuration *replay_configuration)
Austin Schuhfa895892020-01-07 20:07:41 -0800835 : LogReader(std::vector<std::string>{std::string(filename)},
836 replay_configuration) {}
837
838LogReader::LogReader(const std::vector<std::string> &filenames,
839 const Configuration *replay_configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800840 : LogReader(std::vector<std::vector<std::string>>{filenames},
841 replay_configuration) {}
842
Austin Schuh11d43732020-09-21 17:28:30 -0700843// TODO(austin): Make this the base and kill the others. This has much better
844// context for sorting.
845LogReader::LogReader(const std::vector<LogFile> &log_files,
846 const Configuration *replay_configuration)
847 : LogReader(ToLogReaderVector(log_files), replay_configuration) {}
848
Austin Schuh6f3babe2020-01-26 20:34:50 -0800849LogReader::LogReader(const std::vector<std::vector<std::string>> &filenames,
850 const Configuration *replay_configuration)
851 : filenames_(filenames),
852 log_file_header_(ReadHeader(filenames[0][0])),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800853 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800854 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800855
Austin Schuh6aa77be2020-02-22 21:06:40 -0800856 if (replay_configuration) {
857 CHECK_EQ(configuration::MultiNode(configuration()),
858 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700859 << ": Log file and replay config need to both be multi or single "
860 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800861 }
862
Austin Schuh6f3babe2020-01-26 20:34:50 -0800863 if (!configuration::MultiNode(configuration())) {
Austin Schuh858c9f32020-08-31 16:56:12 -0700864 states_.emplace_back(
865 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames)));
Austin Schuh8bd96322020-02-13 21:18:22 -0800866 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800867 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700868 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800869 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700870 << ": Log file and replay config need to have matching nodes "
871 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700872 for (const Node *node : *logged_configuration()->nodes()) {
873 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700874 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
875 << " in logged config that is not present in the replay "
876 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700877 }
878 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800879 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800880 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800881 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800882}
883
Austin Schuh6aa77be2020-02-22 21:06:40 -0800884LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700885 if (event_loop_factory_unique_ptr_) {
886 Deregister();
887 } else if (event_loop_factory_ != nullptr) {
888 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
889 "is destroyed";
890 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800891 if (offset_fp_ != nullptr) {
892 fclose(offset_fp_);
893 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700894 // Zero out some buffers. It's easy to do use-after-frees on these, so make
895 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -0700896 if (remapped_configuration_buffer_) {
897 remapped_configuration_buffer_->Wipe();
898 }
899 log_file_header_.Wipe();
Austin Schuh8bd96322020-02-13 21:18:22 -0800900}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800901
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800902const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800903 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800904}
905
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800906const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800907 return remapped_configuration_;
908}
909
Austin Schuh6f3babe2020-01-26 20:34:50 -0800910std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700911 // Because the Node pointer will only be valid if it actually points to
912 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800913 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800914 //
915 // Also, note, that when ever a map is changed, the nodes in here are
916 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800917 CHECK(remapped_configuration_ != nullptr)
918 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800919 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800920}
Austin Schuh15649d62019-12-28 16:36:38 -0800921
Austin Schuh11d43732020-09-21 17:28:30 -0700922monotonic_clock::time_point LogReader::monotonic_start_time(
923 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800924 State *state =
925 states_[configuration::GetNodeIndex(configuration(), node)].get();
926 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
927
Austin Schuh858c9f32020-08-31 16:56:12 -0700928 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800929}
930
Austin Schuh11d43732020-09-21 17:28:30 -0700931realtime_clock::time_point LogReader::realtime_start_time(
932 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -0800933 State *state =
934 states_[configuration::GetNodeIndex(configuration(), node)].get();
935 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
936
Austin Schuh858c9f32020-08-31 16:56:12 -0700937 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800938}
939
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800940void LogReader::Register() {
941 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800942 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800943 Register(event_loop_factory_unique_ptr_.get());
944}
945
Austin Schuh92547522019-12-28 14:33:43 -0800946void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800947 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -0700948 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh92547522019-12-28 14:33:43 -0800949
Brian Silvermand90905f2020-09-23 14:42:56 -0700950 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800951 const size_t node_index =
952 configuration::GetNodeIndex(configuration(), node);
Austin Schuh858c9f32020-08-31 16:56:12 -0700953 states_[node_index] =
954 std::make_unique<State>(std::make_unique<ChannelMerger>(filenames_));
Austin Schuh8bd96322020-02-13 21:18:22 -0800955 State *state = states_[node_index].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800956
Austin Schuh858c9f32020-08-31 16:56:12 -0700957 Register(state->SetNodeEventLoopFactory(
958 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuhcde938c2020-02-02 17:30:07 -0800959 }
James Kuszmaul46d82582020-05-09 19:50:09 -0700960 if (live_nodes_ == 0) {
961 LOG(FATAL)
962 << "Don't have logs from any of the nodes in the replay config--are "
963 "you sure that the replay config matches the original config?";
964 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800965
Austin Schuh2f8fd752020-09-01 22:38:28 -0700966 // We need to now seed our per-node time offsets and get everything set up
967 // to run.
968 const size_t num_nodes = nodes_count();
Austin Schuhcde938c2020-02-02 17:30:07 -0800969
Austin Schuh8bd96322020-02-13 21:18:22 -0800970 // It is easiest to solve for per node offsets with a matrix rather than
971 // trying to solve the equations by hand. So let's get after it.
972 //
973 // Now, build up the map matrix.
974 //
Austin Schuh2f8fd752020-09-01 22:38:28 -0700975 // offset_matrix_ = (map_matrix_ + slope_matrix_) * [ta; tb; tc]
976 map_matrix_ = Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
977 filters_.size() + 1, num_nodes);
978 slope_matrix_ =
979 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>::Zero(
980 filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800981
Austin Schuh2f8fd752020-09-01 22:38:28 -0700982 offset_matrix_ =
983 Eigen::Matrix<mpq_class, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
984 valid_matrix_ =
985 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
986 last_valid_matrix_ =
987 Eigen::Matrix<bool, Eigen::Dynamic, 1>::Zero(filters_.size() + 1);
Austin Schuhcde938c2020-02-02 17:30:07 -0800988
Austin Schuh2f8fd752020-09-01 22:38:28 -0700989 time_offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
990 time_slope_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuh8bd96322020-02-13 21:18:22 -0800991
Austin Schuh2f8fd752020-09-01 22:38:28 -0700992 // All times should average out to the distributed clock.
993 for (int i = 0; i < map_matrix_.cols(); ++i) {
994 // 1/num_nodes.
995 map_matrix_(0, i) = mpq_class(1, num_nodes);
996 }
997 valid_matrix_(0) = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800998
999 {
1000 // Now, add the a - b -> sample elements.
1001 size_t i = 1;
1002 for (std::pair<const std::tuple<const Node *, const Node *>,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001003 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1004 &filter : filters_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001005 const Node *const node_a = std::get<0>(filter.first);
1006 const Node *const node_b = std::get<1>(filter.first);
1007
1008 const size_t node_a_index =
1009 configuration::GetNodeIndex(configuration(), node_a);
1010 const size_t node_b_index =
1011 configuration::GetNodeIndex(configuration(), node_b);
1012
Austin Schuh2f8fd752020-09-01 22:38:28 -07001013 // -a
1014 map_matrix_(i, node_a_index) = mpq_class(-1);
1015 // +b
1016 map_matrix_(i, node_b_index) = mpq_class(1);
Austin Schuh8bd96322020-02-13 21:18:22 -08001017
1018 // -> sample
Austin Schuh2f8fd752020-09-01 22:38:28 -07001019 std::get<0>(filter.second)
1020 .set_slope_pointer(&slope_matrix_(i, node_a_index));
1021 std::get<0>(filter.second).set_offset_pointer(&offset_matrix_(i, 0));
1022
1023 valid_matrix_(i) = false;
1024 std::get<0>(filter.second).set_valid_pointer(&valid_matrix_(i));
Austin Schuh8bd96322020-02-13 21:18:22 -08001025
1026 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001027 }
1028 }
1029
Austin Schuh858c9f32020-08-31 16:56:12 -07001030 for (std::unique_ptr<State> &state : states_) {
1031 state->SeedSortedMessages();
1032 }
1033
Austin Schuh2f8fd752020-09-01 22:38:28 -07001034 // Rank of the map matrix tells you if all the nodes are in communication
1035 // with each other, which tells you if the offsets are observable.
1036 const size_t connected_nodes =
1037 Eigen::FullPivLU<
1038 Eigen::Matrix<mpq_class, Eigen::Dynamic, Eigen::Dynamic>>(map_matrix_)
1039 .rank();
1040
1041 // We don't need to support isolated nodes until someone has a real use
1042 // case.
1043 CHECK_EQ(connected_nodes, num_nodes)
1044 << ": There is a node which isn't communicating with the rest.";
1045
1046 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001047 UpdateOffsets();
1048
Austin Schuh2f8fd752020-09-01 22:38:28 -07001049 // We want to start the log file at the last start time of the log files
1050 // from all the nodes. Compute how long each node's simulation needs to run
1051 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001052 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001053
Austin Schuh2f8fd752020-09-01 22:38:28 -07001054 // TODO(austin): We want an "OnStart" callback for each node rather than
1055 // running until the last node.
1056
Austin Schuh8bd96322020-02-13 21:18:22 -08001057 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001058 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1059 << MaybeNodeName(state->event_loop()->node()) << "now "
1060 << state->monotonic_now();
1061 // And start computing the start time on the distributed clock now that
1062 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001063 start_time = std::max(
1064 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001065 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001066
1067 CHECK_GE(start_time, distributed_clock::epoch())
1068 << ": Hmm, we have a node starting before the start of time. Offset "
1069 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001070
Austin Schuh6f3babe2020-01-26 20:34:50 -08001071 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1072 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001073 // nodes, and also replayed on the other nodes. This may not satisfy all
1074 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001075 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1076 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1077 const Channel *channel = logged_configuration()->channels()->Get(i);
1078 const Node *node = configuration::GetNode(
1079 configuration(), channel->source_node()->string_view());
1080
Austin Schuh8bd96322020-02-13 21:18:22 -08001081 State *state =
1082 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001083
1084 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001085 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001086
1087 event_loop_factory_->DisableForwarding(remapped_channel);
1088 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001089
1090 // If we are replaying a log, we don't want a bunch of redundant messages
1091 // from both the real message bridge and simulated message bridge.
1092 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001093 }
1094
Austin Schuhcde938c2020-02-02 17:30:07 -08001095 // While we are starting the system up, we might be relying on matching data
1096 // to timestamps on log files where the timestamp log file starts before the
1097 // data. In this case, it is reasonable to expect missing data.
1098 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001099 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001100 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001101 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001102 // Now that we are running for real, missing data means that the log file is
1103 // corrupted or went wrong.
1104 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001105
Austin Schuh8bd96322020-02-13 21:18:22 -08001106 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001107 // Make the RT clock be correct before handing it to the user.
1108 if (state->realtime_start_time() != realtime_clock::min_time) {
1109 state->SetRealtimeOffset(state->monotonic_start_time(),
1110 state->realtime_start_time());
1111 }
1112 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1113 << MaybeNodeName(state->event_loop()->node()) << "now "
1114 << state->monotonic_now();
1115 }
1116
1117 if (FLAGS_timestamps_to_csv) {
1118 for (std::pair<const std::tuple<const Node *, const Node *>,
1119 std::tuple<message_bridge::NoncausalOffsetEstimator>>
1120 &filter : filters_) {
1121 const Node *const node_a = std::get<0>(filter.first);
1122 const Node *const node_b = std::get<1>(filter.first);
1123
1124 std::get<0>(filter.second)
1125 .SetFirstFwdTime(event_loop_factory_->GetNodeEventLoopFactory(node_a)
1126 ->monotonic_now());
1127 std::get<0>(filter.second)
1128 .SetFirstRevTime(event_loop_factory_->GetNodeEventLoopFactory(node_b)
1129 ->monotonic_now());
1130 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001131 }
1132}
1133
Austin Schuh2f8fd752020-09-01 22:38:28 -07001134void LogReader::UpdateOffsets() {
1135 VLOG(2) << "Samples are " << offset_matrix_;
1136 VLOG(2) << "Map is " << (map_matrix_ + slope_matrix_);
1137 std::tie(time_slope_matrix_, time_offset_matrix_) = SolveOffsets();
1138 Eigen::IOFormat HeavyFmt(Eigen::FullPrecision, 0, ", ", ";\n", "[", "]", "[",
1139 "]");
1140 VLOG(1) << "First slope " << time_slope_matrix_.transpose().format(HeavyFmt)
1141 << " offset " << time_offset_matrix_.transpose().format(HeavyFmt);
1142
1143 size_t node_index = 0;
1144 for (std::unique_ptr<State> &state : states_) {
1145 state->SetDistributedOffset(offset(node_index), slope(node_index));
1146 VLOG(1) << "Offset for node " << node_index << " "
1147 << MaybeNodeName(state->event_loop()->node()) << "is "
1148 << aos::distributed_clock::time_point(offset(node_index))
1149 << " slope " << std::setprecision(9) << std::fixed
1150 << slope(node_index);
1151 ++node_index;
1152 }
1153
1154 if (VLOG_IS_ON(1)) {
1155 LogFit("Offset is");
1156 }
1157}
1158
1159void LogReader::LogFit(std::string_view prefix) {
1160 for (std::unique_ptr<State> &state : states_) {
1161 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << " now "
1162 << state->monotonic_now() << " distributed "
1163 << event_loop_factory_->distributed_now();
1164 }
1165
1166 for (std::pair<const std::tuple<const Node *, const Node *>,
1167 std::tuple<message_bridge::NoncausalOffsetEstimator>> &filter :
1168 filters_) {
1169 message_bridge::NoncausalOffsetEstimator *estimator =
1170 &std::get<0>(filter.second);
1171
1172 if (estimator->a_timestamps().size() == 0 &&
1173 estimator->b_timestamps().size() == 0) {
1174 continue;
1175 }
1176
1177 if (VLOG_IS_ON(1)) {
1178 estimator->LogFit(prefix);
1179 }
1180
1181 const Node *const node_a = std::get<0>(filter.first);
1182 const Node *const node_b = std::get<1>(filter.first);
1183
1184 const size_t node_a_index =
1185 configuration::GetNodeIndex(configuration(), node_a);
1186 const size_t node_b_index =
1187 configuration::GetNodeIndex(configuration(), node_b);
1188
1189 const double recovered_slope =
1190 slope(node_b_index) / slope(node_a_index) - 1.0;
1191 const int64_t recovered_offset =
1192 offset(node_b_index).count() - offset(node_a_index).count() *
1193 slope(node_b_index) /
1194 slope(node_a_index);
1195
1196 VLOG(1) << "Recovered slope " << std::setprecision(20) << recovered_slope
1197 << " (error " << recovered_slope - estimator->fit().slope() << ") "
1198 << " offset " << std::setprecision(20) << recovered_offset
1199 << " (error "
1200 << recovered_offset - estimator->fit().offset().count() << ")";
1201
1202 const aos::distributed_clock::time_point a0 =
1203 states_[node_a_index]->ToDistributedClock(
1204 std::get<0>(estimator->a_timestamps()[0]));
1205 const aos::distributed_clock::time_point a1 =
1206 states_[node_a_index]->ToDistributedClock(
1207 std::get<0>(estimator->a_timestamps()[1]));
1208
1209 VLOG(1) << node_a->name()->string_view() << " timestamps()[0] = "
1210 << std::get<0>(estimator->a_timestamps()[0]) << " -> " << a0
1211 << " distributed -> " << node_b->name()->string_view() << " "
1212 << states_[node_b_index]->FromDistributedClock(a0) << " should be "
1213 << aos::monotonic_clock::time_point(
1214 std::chrono::nanoseconds(static_cast<int64_t>(
1215 std::get<0>(estimator->a_timestamps()[0])
1216 .time_since_epoch()
1217 .count() *
1218 (1.0 + estimator->fit().slope()))) +
1219 estimator->fit().offset())
1220 << ((a0 <= event_loop_factory_->distributed_now())
1221 ? ""
1222 : " After now, investigate");
1223 VLOG(1) << node_a->name()->string_view() << " timestamps()[1] = "
1224 << std::get<0>(estimator->a_timestamps()[1]) << " -> " << a1
1225 << " distributed -> " << node_b->name()->string_view() << " "
1226 << states_[node_b_index]->FromDistributedClock(a1) << " should be "
1227 << aos::monotonic_clock::time_point(
1228 std::chrono::nanoseconds(static_cast<int64_t>(
1229 std::get<0>(estimator->a_timestamps()[1])
1230 .time_since_epoch()
1231 .count() *
1232 (1.0 + estimator->fit().slope()))) +
1233 estimator->fit().offset())
1234 << ((event_loop_factory_->distributed_now() <= a1)
1235 ? ""
1236 : " Before now, investigate");
1237
1238 const aos::distributed_clock::time_point b0 =
1239 states_[node_b_index]->ToDistributedClock(
1240 std::get<0>(estimator->b_timestamps()[0]));
1241 const aos::distributed_clock::time_point b1 =
1242 states_[node_b_index]->ToDistributedClock(
1243 std::get<0>(estimator->b_timestamps()[1]));
1244
1245 VLOG(1) << node_b->name()->string_view() << " timestamps()[0] = "
1246 << std::get<0>(estimator->b_timestamps()[0]) << " -> " << b0
1247 << " distributed -> " << node_a->name()->string_view() << " "
1248 << states_[node_a_index]->FromDistributedClock(b0)
1249 << ((b0 <= event_loop_factory_->distributed_now())
1250 ? ""
1251 : " After now, investigate");
1252 VLOG(1) << node_b->name()->string_view() << " timestamps()[1] = "
1253 << std::get<0>(estimator->b_timestamps()[1]) << " -> " << b1
1254 << " distributed -> " << node_a->name()->string_view() << " "
1255 << states_[node_a_index]->FromDistributedClock(b1)
1256 << ((event_loop_factory_->distributed_now() <= b1)
1257 ? ""
1258 : " Before now, investigate");
1259 }
1260}
1261
1262message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001263 const Node *node_a, const Node *node_b) {
1264 CHECK_NE(node_a, node_b);
1265 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
1266 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
1267
1268 if (node_a > node_b) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001269 return GetFilter(node_b, node_a);
Austin Schuh8bd96322020-02-13 21:18:22 -08001270 }
1271
1272 auto tuple = std::make_tuple(node_a, node_b);
1273
1274 auto it = filters_.find(tuple);
1275
1276 if (it == filters_.end()) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001277 auto &x =
1278 filters_
1279 .insert(std::make_pair(
1280 tuple, std::make_tuple(message_bridge::NoncausalOffsetEstimator(
1281 node_a, node_b))))
1282 .first->second;
Austin Schuh8bd96322020-02-13 21:18:22 -08001283 if (FLAGS_timestamps_to_csv) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001284 std::get<0>(x).SetFwdCsvFileName(absl::StrCat(
1285 "/tmp/timestamp_noncausal_", node_a->name()->string_view(), "_",
1286 node_b->name()->string_view()));
1287 std::get<0>(x).SetRevCsvFileName(absl::StrCat(
1288 "/tmp/timestamp_noncausal_", node_b->name()->string_view(), "_",
1289 node_a->name()->string_view()));
Austin Schuh8bd96322020-02-13 21:18:22 -08001290 }
1291
Austin Schuh2f8fd752020-09-01 22:38:28 -07001292 return &std::get<0>(x);
Austin Schuh8bd96322020-02-13 21:18:22 -08001293 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001294 return &std::get<0>(it->second);
Austin Schuh8bd96322020-02-13 21:18:22 -08001295 }
1296}
1297
Austin Schuhe309d2a2019-11-29 13:25:21 -08001298void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001299 State *state =
1300 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1301 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001302
Austin Schuh858c9f32020-08-31 16:56:12 -07001303 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001304
Tyler Chatow67ddb032020-01-12 14:30:04 -08001305 // We don't run timing reports when trying to print out logged data, because
1306 // otherwise we would end up printing out the timing reports themselves...
1307 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001308 event_loop->SkipTimingReport();
1309 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001310
Austin Schuh858c9f32020-08-31 16:56:12 -07001311 const bool has_data = state->SetNode();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001312
Austin Schuh858c9f32020-08-31 16:56:12 -07001313 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuh8bd96322020-02-13 21:18:22 -08001314
Austin Schuh858c9f32020-08-31 16:56:12 -07001315 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001316 const Channel *channel =
1317 RemapChannel(event_loop, logged_configuration()->channels()->Get(i));
Austin Schuh6331ef92020-01-07 18:28:09 -08001318
Austin Schuh858c9f32020-08-31 16:56:12 -07001319 NodeEventLoopFactory *channel_target_event_loop_factory = nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001320 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001321
1322 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1323 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
1324 const Node *target_node = configuration::GetNode(
1325 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh858c9f32020-08-31 16:56:12 -07001326 filter = GetFilter(event_loop->node(), target_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001327
1328 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001329 channel_target_event_loop_factory =
Austin Schuh8bd96322020-02-13 21:18:22 -08001330 event_loop_factory_->GetNodeEventLoopFactory(target_node);
1331 }
1332 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001333
1334 state->SetChannel(i, event_loop->MakeRawSender(channel), filter,
1335 channel_target_event_loop_factory);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001336 }
1337
Austin Schuh6aa77be2020-02-22 21:06:40 -08001338 // If we didn't find any log files with data in them, we won't ever get a
1339 // callback or be live. So skip the rest of the setup.
1340 if (!has_data) {
1341 return;
1342 }
1343
Austin Schuh858c9f32020-08-31 16:56:12 -07001344 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001345 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1346 << "at " << state->event_loop()->context().monotonic_event_time
1347 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001348 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001349 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001350 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001351 if (live_nodes_ == 0) {
1352 event_loop_factory_->Exit();
1353 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001354 return;
1355 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001356 TimestampMerger::DeliveryTimestamp channel_timestamp;
Austin Schuh05b70472020-01-01 17:11:17 -08001357 int channel_index;
1358 FlatbufferVector<MessageHeader> channel_data =
1359 FlatbufferVector<MessageHeader>::Empty();
1360
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 if (VLOG_IS_ON(1)) {
1362 LogFit("Offset was");
1363 }
1364
1365 bool update_time;
Austin Schuh05b70472020-01-01 17:11:17 -08001366 std::tie(channel_timestamp, channel_index, channel_data) =
Austin Schuh2f8fd752020-09-01 22:38:28 -07001367 state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001368
Austin Schuhe309d2a2019-11-29 13:25:21 -08001369 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001370 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001371 if (!FLAGS_skip_order_validation) {
1372 CHECK(monotonic_now == channel_timestamp.monotonic_event_time)
1373 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1374 << monotonic_now << " trying to send "
1375 << channel_timestamp.monotonic_event_time << " failure "
1376 << state->DebugString();
1377 } else if (monotonic_now != channel_timestamp.monotonic_event_time) {
1378 LOG(WARNING) << "Check failed: monotonic_now == "
1379 "channel_timestamp.monotonic_event_time) ("
1380 << monotonic_now << " vs. "
1381 << channel_timestamp.monotonic_event_time
1382 << "): " << FlatbufferToJson(state->event_loop()->node())
1383 << " Now " << monotonic_now << " trying to send "
1384 << channel_timestamp.monotonic_event_time << " failure "
1385 << state->DebugString();
1386 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001387
Austin Schuh6f3babe2020-01-26 20:34:50 -08001388 if (channel_timestamp.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001389 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001390 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001391 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001392 !state->at_end()) ||
Austin Schuh05b70472020-01-01 17:11:17 -08001393 channel_data.message().data() != nullptr) {
1394 CHECK(channel_data.message().data() != nullptr)
1395 << ": Got a message without data. Forwarding entry which was "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001396 "not matched? Use --skip_missing_forwarding_entries to "
Brian Silverman87ac0402020-09-17 14:47:01 -07001397 "ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001398
Austin Schuh2f8fd752020-09-01 22:38:28 -07001399 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001400 // Confirm that the message was sent on the sending node before the
1401 // destination node (this node). As a proxy, do this by making sure
1402 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001403 if (!FLAGS_skip_order_validation) {
1404 CHECK_LT(channel_timestamp.monotonic_remote_time,
1405 state->monotonic_remote_now(channel_index))
1406 << state->event_loop()->node()->name()->string_view() << " to "
1407 << state->remote_node(channel_index)->name()->string_view()
1408 << " " << state->DebugString();
1409 } else if (channel_timestamp.monotonic_remote_time >=
1410 state->monotonic_remote_now(channel_index)) {
1411 LOG(WARNING)
1412 << "Check failed: channel_timestamp.monotonic_remote_time < "
1413 "state->monotonic_remote_now(channel_index) ("
1414 << channel_timestamp.monotonic_remote_time << " vs. "
1415 << state->monotonic_remote_now(channel_index) << ") "
1416 << state->event_loop()->node()->name()->string_view() << " to "
1417 << state->remote_node(channel_index)->name()->string_view()
1418 << " currently " << channel_timestamp.monotonic_event_time
1419 << " ("
1420 << state->ToDistributedClock(
1421 channel_timestamp.monotonic_event_time)
1422 << ") remote event time "
1423 << channel_timestamp.monotonic_remote_time << " ("
1424 << state->RemoteToDistributedClock(
1425 channel_index, channel_timestamp.monotonic_remote_time)
1426 << ") " << state->DebugString();
1427 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001428
1429 if (FLAGS_timestamps_to_csv) {
1430 if (offset_fp_ == nullptr) {
1431 offset_fp_ = fopen("/tmp/offsets.csv", "w");
1432 fprintf(
1433 offset_fp_,
1434 "# time_since_start, offset node 0, offset node 1, ...\n");
1435 first_time_ = channel_timestamp.realtime_event_time;
1436 }
1437
1438 fprintf(offset_fp_, "%.9f",
1439 std::chrono::duration_cast<std::chrono::duration<double>>(
1440 channel_timestamp.realtime_event_time - first_time_)
1441 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001442 for (int i = 1; i < time_offset_matrix_.rows(); ++i) {
1443 fprintf(offset_fp_, ", %.9f",
1444 time_offset_matrix_(i, 0) +
1445 time_slope_matrix_(i, 0) *
1446 chrono::duration<double>(
1447 event_loop_factory_->distributed_now()
1448 .time_since_epoch())
1449 .count());
Austin Schuh8bd96322020-02-13 21:18:22 -08001450 }
1451 fprintf(offset_fp_, "\n");
1452 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001453 }
1454
Austin Schuh15649d62019-12-28 16:36:38 -08001455 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh858c9f32020-08-31 16:56:12 -07001456 state->SetRealtimeOffset(channel_timestamp.monotonic_event_time,
1457 channel_timestamp.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001458
Austin Schuh2f8fd752020-09-01 22:38:28 -07001459 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
1460 << channel_timestamp.monotonic_event_time;
1461 // TODO(austin): std::move channel_data in and make that efficient in
1462 // simulation.
Austin Schuh858c9f32020-08-31 16:56:12 -07001463 state->Send(channel_index, channel_data.message().data()->Data(),
1464 channel_data.message().data()->size(),
1465 channel_timestamp.monotonic_remote_time,
1466 channel_timestamp.realtime_remote_time,
1467 channel_timestamp.remote_queue_index);
Austin Schuh2f8fd752020-09-01 22:38:28 -07001468 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001469 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001470 // reading the rest of the log file and call it quits. We don't want
1471 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001472 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1473 bool update_time_dummy;
1474 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001475 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001476 } else {
1477 CHECK(channel_data.message().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001478 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001479 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001480 LOG(WARNING)
1481 << "Not sending data from before the start of the log file. "
1482 << channel_timestamp.monotonic_event_time.time_since_epoch().count()
1483 << " start " << monotonic_start_time().time_since_epoch().count()
1484 << " " << FlatbufferToJson(channel_data);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001485 }
1486
Austin Schuh858c9f32020-08-31 16:56:12 -07001487 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001488 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001489 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1490 << "wakeup for " << next_time << "("
1491 << state->ToDistributedClock(next_time)
1492 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001493 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001494 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001495 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1496 << "No next message, scheduling shutdown";
1497 // Set a timer up immediately after now to die. If we don't do this,
1498 // then the senders waiting on the message we just read will never get
1499 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001500 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001501 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1502 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001503 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001504 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001505
Austin Schuh2f8fd752020-09-01 22:38:28 -07001506 // Once we make this call, the current time changes. So do everything
1507 // which involves time before changing it. That especially includes
1508 // sending the message.
1509 if (update_time) {
1510 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1511 << "updating offsets";
1512
1513 std::vector<aos::monotonic_clock::time_point> before_times;
1514 before_times.resize(states_.size());
1515 std::transform(states_.begin(), states_.end(), before_times.begin(),
1516 [](const std::unique_ptr<State> &state) {
1517 return state->monotonic_now();
1518 });
1519
1520 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001521 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "before "
1522 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001523 }
1524
Austin Schuh8bd96322020-02-13 21:18:22 -08001525 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001526 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1527 << state->monotonic_now();
1528
1529 for (size_t i = 0; i < states_.size(); ++i) {
Brian Silvermand90905f2020-09-23 14:42:56 -07001530 VLOG(1) << MaybeNodeName(states_[i]->event_loop()->node()) << "after "
1531 << states_[i]->monotonic_now();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001532 }
1533
1534 // TODO(austin): We should be perfect.
1535 const std::chrono::nanoseconds kTolerance{3};
1536 if (!FLAGS_skip_order_validation) {
1537 CHECK_GE(next_time, state->monotonic_now())
1538 << ": Time skipped the next event.";
1539
1540 for (size_t i = 0; i < states_.size(); ++i) {
1541 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1542 << ": Time changed too much on node "
1543 << MaybeNodeName(states_[i]->event_loop()->node());
1544 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1545 << ": Time changed too much on node "
1546 << states_[i]->event_loop()->node()->name()->string_view();
1547 }
1548 } else {
1549 if (next_time < state->monotonic_now()) {
1550 LOG(WARNING) << "Check failed: next_time >= "
1551 "state->monotonic_now() ("
1552 << next_time << " vs. " << state->monotonic_now()
1553 << "): Time skipped the next event.";
1554 }
1555 for (size_t i = 0; i < states_.size(); ++i) {
1556 if (states_[i]->monotonic_now() >= before_times[i] - kTolerance) {
1557 LOG(WARNING) << "Check failed: "
1558 "states_[i]->monotonic_now() "
1559 ">= before_times[i] - kTolerance ("
1560 << states_[i]->monotonic_now() << " vs. "
1561 << before_times[i] - kTolerance
1562 << ") : Time changed too much on node "
1563 << MaybeNodeName(states_[i]->event_loop()->node());
1564 }
1565 if (states_[i]->monotonic_now() <= before_times[i] + kTolerance) {
1566 LOG(WARNING) << "Check failed: "
1567 "states_[i]->monotonic_now() "
1568 "<= before_times[i] + kTolerance ("
1569 << states_[i]->monotonic_now() << " vs. "
1570 << before_times[i] - kTolerance
1571 << ") : Time changed too much on node "
1572 << MaybeNodeName(states_[i]->event_loop()->node());
1573 }
1574 }
1575 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001576 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001577
1578 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1579 << state->event_loop()->context().monotonic_event_time << " now "
1580 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001581 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001582
Austin Schuh6f3babe2020-01-26 20:34:50 -08001583 ++live_nodes_;
1584
Austin Schuh858c9f32020-08-31 16:56:12 -07001585 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1586 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001587 }
1588}
1589
1590void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001591 // Make sure that things get destroyed in the correct order, rather than
1592 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001593 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001594 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001595 }
Austin Schuh92547522019-12-28 14:33:43 -08001596
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001597 event_loop_factory_unique_ptr_.reset();
1598 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001599}
1600
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001601void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1602 std::string_view add_prefix) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001603 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1604 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1605 if (channel->name()->str() == name &&
1606 channel->type()->string_view() == type) {
1607 CHECK_EQ(0u, remapped_channels_.count(ii))
1608 << "Already remapped channel "
1609 << configuration::CleanedChannelToString(channel);
1610 remapped_channels_[ii] = std::string(add_prefix) + std::string(name);
1611 VLOG(1) << "Remapping channel "
1612 << configuration::CleanedChannelToString(channel)
1613 << " to have name " << remapped_channels_[ii];
Austin Schuh6331ef92020-01-07 18:28:09 -08001614 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001615 return;
1616 }
1617 }
1618 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1619 << type;
1620}
1621
Austin Schuh01b4c352020-09-21 23:09:39 -07001622void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1623 const Node *node,
1624 std::string_view add_prefix) {
1625 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1626 const Channel *remapped_channel =
1627 configuration::GetChannel(logged_configuration(), name, type, "", node);
1628 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1629 << "\", \"type\": \"" << type << "\"}";
1630 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1631 << "\"}";
1632 VLOG(1) << "Remapped "
1633 << aos::configuration::StrippedChannelToString(remapped_channel);
1634
1635 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1636 // we want it to degrade if the heuristics fail to just work.
1637 //
1638 // The easiest way to do this is going to be incredibly specific and verbose.
1639 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1640 // /original/0/spray. Then, create a map from /original/spray to
1641 // /original/0/spray for just the type we were asked for.
1642 if (name != remapped_channel->name()->string_view()) {
1643 MapT new_map;
1644 new_map.match = std::make_unique<ChannelT>();
1645 new_map.match->name = absl::StrCat(add_prefix, name);
1646 new_map.match->type = type;
1647 if (node != nullptr) {
1648 new_map.match->source_node = node->name()->str();
1649 }
1650 new_map.rename = std::make_unique<ChannelT>();
1651 new_map.rename->name =
1652 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1653 maps_.emplace_back(std::move(new_map));
1654 }
1655
1656 const size_t channel_index =
1657 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1658 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1659 << "Already remapped channel "
1660 << configuration::CleanedChannelToString(remapped_channel);
1661 remapped_channels_[channel_index] =
1662 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1663 MakeRemappedConfig();
1664}
1665
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001666void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001667 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001668 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001669 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001670 << ": Can't change the mapping after the events are scheduled.";
1671 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001672 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001673
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001674 // If no remapping occurred and we are using the original config, then there
1675 // is nothing interesting to do here.
1676 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001677 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001678 return;
1679 }
1680 // Config to copy Channel definitions from. Use the specified
1681 // replay_configuration_ if it has been provided.
1682 const Configuration *const base_config = replay_configuration_ == nullptr
1683 ? logged_configuration()
1684 : replay_configuration_;
1685 // The remapped config will be identical to the base_config, except that it
1686 // will have a bunch of extra channels in the channel list, which are exact
1687 // copies of the remapped channels, but with different names.
1688 // Because the flatbuffers API is a pain to work with, this requires a bit of
1689 // a song-and-dance to get copied over.
1690 // The order of operations is to:
1691 // 1) Make a flatbuffer builder for a config that will just contain a list of
1692 // the new channels that we want to add.
1693 // 2) For each channel that we are remapping:
1694 // a) Make a buffer/builder and construct into it a Channel table that only
1695 // contains the new name for the channel.
1696 // b) Merge the new channel with just the name into the channel that we are
1697 // trying to copy, built in the flatbuffer builder made in 1. This gives
1698 // us the new channel definition that we need.
1699 // 3) Using this list of offsets, build the Configuration of just new
1700 // Channels.
1701 // 4) Merge the Configuration with the new Channels into the base_config.
1702 // 5) Call MergeConfiguration() on that result to give MergeConfiguration a
1703 // chance to sanitize the config.
1704
1705 // This is the builder that we use for the config containing all the new
1706 // channels.
1707 flatbuffers::FlatBufferBuilder new_config_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001708 new_config_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001709 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
1710 for (auto &pair : remapped_channels_) {
1711 // This is the builder that we use for creating the Channel with just the
1712 // new name.
1713 flatbuffers::FlatBufferBuilder new_name_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -08001714 new_name_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001715 const flatbuffers::Offset<flatbuffers::String> name_offset =
1716 new_name_fbb.CreateString(pair.second);
1717 ChannelBuilder new_name_builder(new_name_fbb);
1718 new_name_builder.add_name(name_offset);
1719 new_name_fbb.Finish(new_name_builder.Finish());
1720 const FlatbufferDetachedBuffer<Channel> new_name = new_name_fbb.Release();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001721 // Retrieve the channel that we want to copy, confirming that it is
1722 // actually present in base_config.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001723 const Channel *const base_channel = CHECK_NOTNULL(configuration::GetChannel(
1724 base_config, logged_configuration()->channels()->Get(pair.first), "",
1725 nullptr));
1726 // Actually create the new channel and put it into the vector of Offsets
1727 // that we will use to create the new Configuration.
1728 channel_offsets.emplace_back(MergeFlatBuffers<Channel>(
1729 reinterpret_cast<const flatbuffers::Table *>(base_channel),
1730 reinterpret_cast<const flatbuffers::Table *>(&new_name.message()),
1731 &new_config_fbb));
1732 }
1733 // Create the Configuration containing the new channels that we want to add.
Austin Schuh01b4c352020-09-21 23:09:39 -07001734 const auto new_channel_vector_offsets =
Austin Schuhfa895892020-01-07 20:07:41 -08001735 new_config_fbb.CreateVector(channel_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001736
1737 // Now create the new maps.
1738 std::vector<flatbuffers::Offset<Map>> map_offsets;
1739 for (const MapT &map : maps_) {
1740 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
1741 new_config_fbb.CreateString(map.match->name);
1742 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
1743 new_config_fbb.CreateString(map.match->type);
1744 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
1745 new_config_fbb.CreateString(map.rename->name);
1746 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1747 if (!map.match->source_node.empty()) {
1748 match_source_node_offset =
1749 new_config_fbb.CreateString(map.match->source_node);
1750 }
1751 Channel::Builder match_builder(new_config_fbb);
1752 match_builder.add_name(match_name_offset);
1753 match_builder.add_type(match_type_offset);
1754 if (!map.match->source_node.empty()) {
1755 match_builder.add_source_node(match_source_node_offset);
1756 }
1757 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1758
1759 Channel::Builder rename_builder(new_config_fbb);
1760 rename_builder.add_name(rename_name_offset);
1761 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1762
1763 Map::Builder map_builder(new_config_fbb);
1764 map_builder.add_match(match_offset);
1765 map_builder.add_rename(rename_offset);
1766 map_offsets.emplace_back(map_builder.Finish());
1767 }
1768
1769 const auto new_maps_offsets = new_config_fbb.CreateVector(map_offsets);
1770
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001771 ConfigurationBuilder new_config_builder(new_config_fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001772 new_config_builder.add_channels(new_channel_vector_offsets);
1773 new_config_builder.add_maps(new_maps_offsets);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001774 new_config_fbb.Finish(new_config_builder.Finish());
1775 const FlatbufferDetachedBuffer<Configuration> new_name_config =
1776 new_config_fbb.Release();
1777 // Merge the new channels configuration into the base_config, giving us the
1778 // remapped configuration.
1779 remapped_configuration_buffer_ =
1780 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1781 MergeFlatBuffers<Configuration>(base_config,
1782 &new_name_config.message()));
1783 // Call MergeConfiguration to deal with sanitizing the config.
1784 remapped_configuration_buffer_ =
1785 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
1786 configuration::MergeConfiguration(*remapped_configuration_buffer_));
1787
1788 remapped_configuration_ = &remapped_configuration_buffer_->message();
1789}
1790
Austin Schuh6f3babe2020-01-26 20:34:50 -08001791const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1792 const Channel *channel) {
1793 std::string_view channel_name = channel->name()->string_view();
1794 std::string_view channel_type = channel->type()->string_view();
1795 const int channel_index =
1796 configuration::ChannelIndex(logged_configuration(), channel);
1797 // If the channel is remapped, find the correct channel name to use.
1798 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001799 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001800 << configuration::CleanedChannelToString(channel);
1801 channel_name = remapped_channels_[channel_index];
1802 }
1803
Austin Schuhee711052020-08-24 16:06:09 -07001804 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001805 const Channel *remapped_channel = configuration::GetChannel(
1806 event_loop->configuration(), channel_name, channel_type,
1807 event_loop->name(), event_loop->node());
1808
1809 CHECK(remapped_channel != nullptr)
1810 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1811 << channel_type << "\"} because it is not in the provided configuration.";
1812
1813 return remapped_channel;
1814}
1815
Austin Schuh858c9f32020-08-31 16:56:12 -07001816LogReader::State::State(std::unique_ptr<ChannelMerger> channel_merger)
1817 : channel_merger_(std::move(channel_merger)) {}
1818
1819EventLoop *LogReader::State::SetNodeEventLoopFactory(
1820 NodeEventLoopFactory *node_event_loop_factory) {
1821 node_event_loop_factory_ = node_event_loop_factory;
1822 event_loop_unique_ptr_ =
1823 node_event_loop_factory_->MakeEventLoop("log_reader");
1824 return event_loop_unique_ptr_.get();
1825}
1826
1827void LogReader::State::SetChannelCount(size_t count) {
1828 channels_.resize(count);
1829 filters_.resize(count);
1830 channel_target_event_loop_factory_.resize(count);
1831}
1832
1833void LogReader::State::SetChannel(
1834 size_t channel, std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001835 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh858c9f32020-08-31 16:56:12 -07001836 NodeEventLoopFactory *channel_target_event_loop_factory) {
1837 channels_[channel] = std::move(sender);
1838 filters_[channel] = filter;
1839 channel_target_event_loop_factory_[channel] =
1840 channel_target_event_loop_factory;
1841}
1842
1843std::tuple<TimestampMerger::DeliveryTimestamp, int,
1844 FlatbufferVector<MessageHeader>>
1845LogReader::State::PopOldest(bool *update_time) {
1846 CHECK_GT(sorted_messages_.size(), 0u);
1847
1848 std::tuple<TimestampMerger::DeliveryTimestamp, int,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001849 FlatbufferVector<MessageHeader>,
1850 message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001851 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001852 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001853 << std::get<0>(result).monotonic_event_time;
1854 sorted_messages_.pop_front();
1855 SeedSortedMessages();
1856
Austin Schuh2f8fd752020-09-01 22:38:28 -07001857 if (std::get<3>(result) != nullptr) {
1858 *update_time = std::get<3>(result)->Pop(
1859 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1860 } else {
1861 *update_time = false;
1862 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001863 return std::make_tuple(std::get<0>(result), std::get<1>(result),
1864 std::move(std::get<2>(result)));
1865}
1866
1867monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1868 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001869 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001870 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1871 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1872 }
1873
1874 return channel_merger_->OldestMessageTime();
1875}
1876
1877void LogReader::State::SeedSortedMessages() {
1878 const aos::monotonic_clock::time_point end_queue_time =
1879 (sorted_messages_.size() > 0
1880 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
1881 : channel_merger_->monotonic_start_time()) +
1882 std::chrono::seconds(2);
1883
1884 while (true) {
1885 if (channel_merger_->OldestMessageTime() == monotonic_clock::max_time) {
1886 return;
1887 }
1888 if (sorted_messages_.size() > 0) {
1889 // Stop placing sorted messages on the list once we have 2 seconds
1890 // queued up (but queue at least until the log starts.
1891 if (end_queue_time <
1892 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
1893 return;
1894 }
1895 }
1896
1897 TimestampMerger::DeliveryTimestamp channel_timestamp;
1898 int channel_index;
1899 FlatbufferVector<MessageHeader> channel_data =
1900 FlatbufferVector<MessageHeader>::Empty();
1901
Austin Schuh2f8fd752020-09-01 22:38:28 -07001902 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
1903
Austin Schuh858c9f32020-08-31 16:56:12 -07001904 std::tie(channel_timestamp, channel_index, channel_data) =
1905 channel_merger_->PopOldest();
1906
Austin Schuh2f8fd752020-09-01 22:38:28 -07001907 // Skip any messages without forwarding information.
1908 if (channel_timestamp.monotonic_remote_time != monotonic_clock::min_time) {
1909 // Got a forwarding timestamp!
1910 filter = filters_[channel_index];
1911
1912 CHECK(filter != nullptr);
1913
1914 // Call the correct method depending on if we are the forward or
1915 // reverse direction here.
1916 filter->Sample(event_loop_->node(),
1917 channel_timestamp.monotonic_event_time,
1918 channel_timestamp.monotonic_remote_time);
1919 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001920 sorted_messages_.emplace_back(channel_timestamp, channel_index,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001921 std::move(channel_data), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07001922 }
1923}
1924
1925void LogReader::State::Deregister() {
1926 for (size_t i = 0; i < channels_.size(); ++i) {
1927 channels_[i].reset();
1928 }
1929 event_loop_unique_ptr_.reset();
1930 event_loop_ = nullptr;
1931 timer_handler_ = nullptr;
1932 node_event_loop_factory_ = nullptr;
1933}
1934
Austin Schuhe309d2a2019-11-29 13:25:21 -08001935} // namespace logger
1936} // namespace aos