blob: d750caf6270f0deb776d9e926ee39532d702cae5 [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
Austin Schuh4c4e0092019-12-22 16:18:03 -08004#include <limits.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
8#include <vector>
9
Austin Schuh8bd96322020-02-13 21:18:22 -080010#include "Eigen/Dense"
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070014#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080015#include "aos/events/logging/logger_generated.h"
Austin Schuh64fab802020-09-09 22:47:47 -070016#include "aos/events/logging/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080018#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080019#include "aos/network/remote_message_generated.h"
20#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080021#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070023#include "aos/util/file.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "flatbuffers/flatbuffers.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070025#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080026
Austin Schuh15649d62019-12-28 16:36:38 -080027DEFINE_bool(skip_missing_forwarding_entries, false,
28 "If true, drop any forwarding entries with missing data. If "
29 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080030
Austin Schuh0ca1fd32020-12-18 22:53:05 -080031DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080032
Austin Schuh2f8fd752020-09-01 22:38:28 -070033DEFINE_bool(skip_order_validation, false,
34 "If true, ignore any out of orderness in replay");
35
Austin Schuhf0688662020-12-19 15:37:45 -080036DEFINE_double(
37 time_estimation_buffer_seconds, 2.0,
38 "The time to buffer ahead in the log file to accurately reconstruct time.");
39
Austin Schuhe309d2a2019-11-29 13:25:21 -080040namespace aos {
41namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070042namespace {
Austin Schuh315b96b2020-12-11 21:21:12 -080043std::string LogFileVectorToString(std::vector<LogFile> log_files) {
44 std::stringstream ss;
45 for (const auto f : log_files) {
46 ss << f << "\n";
47 }
48 return ss.str();
49}
50
Austin Schuh0de30f32020-12-06 12:44:28 -080051// Copies the channel, removing the schema as we go. If new_name is provided,
52// it is used instead of the name inside the channel. If new_type is provided,
53// it is used instead of the type in the channel.
54flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
55 std::string_view new_name,
56 std::string_view new_type,
57 flatbuffers::FlatBufferBuilder *fbb) {
58 flatbuffers::Offset<flatbuffers::String> name_offset =
59 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
60 : new_name);
61 flatbuffers::Offset<flatbuffers::String> type_offset =
62 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
63 flatbuffers::Offset<flatbuffers::String> source_node_offset =
64 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
65 : 0;
66
67 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
68 destination_nodes_offset =
69 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
70
71 flatbuffers::Offset<
72 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
73 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
74
75 Channel::Builder channel_builder(*fbb);
76 channel_builder.add_name(name_offset);
77 channel_builder.add_type(type_offset);
78 if (c->has_frequency()) {
79 channel_builder.add_frequency(c->frequency());
80 }
81 if (c->has_max_size()) {
82 channel_builder.add_max_size(c->max_size());
83 }
84 if (c->has_num_senders()) {
85 channel_builder.add_num_senders(c->num_senders());
86 }
87 if (c->has_num_watchers()) {
88 channel_builder.add_num_watchers(c->num_watchers());
89 }
90 if (!source_node_offset.IsNull()) {
91 channel_builder.add_source_node(source_node_offset);
92 }
93 if (!destination_nodes_offset.IsNull()) {
94 channel_builder.add_destination_nodes(destination_nodes_offset);
95 }
96 if (c->has_logger()) {
97 channel_builder.add_logger(c->logger());
98 }
99 if (!logger_nodes_offset.IsNull()) {
100 channel_builder.add_logger_nodes(logger_nodes_offset);
101 }
102 if (c->has_read_method()) {
103 channel_builder.add_read_method(c->read_method());
104 }
105 if (c->has_num_readers()) {
106 channel_builder.add_num_readers(c->num_readers());
107 }
108 return channel_builder.Finish();
109}
110
Austin Schuhe309d2a2019-11-29 13:25:21 -0800111namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800112using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700113} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800114
Brian Silverman1f345222020-09-24 21:14:48 -0700115Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
116 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800117 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700118 configuration_(configuration),
119 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700120 timer_handler_(event_loop_->AddTimer(
121 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700122 server_statistics_fetcher_(
123 configuration::MultiNode(event_loop_->configuration())
124 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
125 "/aos")
126 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700127 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700128
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700129 // Find all the nodes which are logging timestamps on our node. This may
130 // over-estimate if should_log is specified.
131 std::vector<const Node *> timestamp_logger_nodes =
132 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700133
134 std::map<const Channel *, const Node *> timestamp_logger_channels;
135
136 // Now that we have all the nodes accumulated, make remote timestamp loggers
137 // for them.
138 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700139 // Note: since we are doing a find using the event loop channel, we need to
140 // make sure this channel pointer is part of the event loop configuration,
141 // not configuration_. This only matters when configuration_ !=
142 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700143 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700144 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700145 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800146 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147 event_loop_->node());
148
149 CHECK(channel != nullptr)
150 << ": Remote timestamps are logged on "
151 << event_loop_->node()->name()->string_view()
152 << " but can't find channel /aos/remote_timestamps/"
153 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700154 if (!should_log(channel)) {
155 continue;
156 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 timestamp_logger_channels.insert(std::make_pair(channel, node));
158 }
159
Brian Silvermand90905f2020-09-23 14:42:56 -0700160 const size_t our_node_index =
161 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700162
Brian Silverman1f345222020-09-24 21:14:48 -0700163 for (size_t channel_index = 0;
164 channel_index < configuration_->channels()->size(); ++channel_index) {
165 const Channel *const config_channel =
166 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700167 // The MakeRawFetcher method needs a channel which is in the event loop
168 // configuration() object, not the configuration_ object. Go look that up
169 // from the config.
170 const Channel *channel = aos::configuration::GetChannel(
171 event_loop_->configuration(), config_channel->name()->string_view(),
172 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700173 CHECK(channel != nullptr)
174 << ": Failed to look up channel "
175 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700176 if (!should_log(channel)) {
177 continue;
178 }
Austin Schuh0c297012020-09-16 18:41:59 -0700179
Austin Schuhe309d2a2019-11-29 13:25:21 -0800180 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700181 fs.channel_index = channel_index;
182 fs.channel = channel;
183
Austin Schuh6f3babe2020-01-26 20:34:50 -0800184 const bool is_local =
185 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
186
Austin Schuh15649d62019-12-28 16:36:38 -0800187 const bool is_readable =
188 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700189 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
190 channel, event_loop_->node());
191 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800192
Brian Silverman1f345222020-09-24 21:14:48 -0700193 bool log_delivery_times = false;
194 if (event_loop_->node() != nullptr) {
195 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
196 channel, event_loop_->node(), event_loop_->node());
197 }
Austin Schuh15649d62019-12-28 16:36:38 -0800198
Austin Schuh0de30f32020-12-06 12:44:28 -0800199 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700200 // contents to a file directly.
201 const bool log_contents = timestamp_logger_channels.find(channel) !=
202 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700203
204 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800205 fs.fetcher = event_loop->MakeRawFetcher(channel);
206 VLOG(1) << "Logging channel "
207 << configuration::CleanedChannelToString(channel);
208
209 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800210 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700211 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800212 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800213 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800214 if (log_message) {
215 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700216 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800217 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800218 const Node *source_node = configuration::GetNode(
219 configuration_, channel->source_node()->string_view());
220 fs.data_node_index =
221 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800222 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800223 } else {
224 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800225 }
226 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700227 if (log_contents) {
228 VLOG(1) << "Timestamp logger channel "
229 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700230 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
231 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800232 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700233 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700234 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800235 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800236 }
Brian Silverman1f345222020-09-24 21:14:48 -0700237 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700238
239 // When we are logging remote timestamps, we need to be able to translate from
240 // the channel index that the event loop uses to the channel index in the
241 // config in the log file.
242 event_loop_to_logged_channel_index_.resize(
243 event_loop->configuration()->channels()->size(), -1);
244 for (size_t event_loop_channel_index = 0;
245 event_loop_channel_index <
246 event_loop->configuration()->channels()->size();
247 ++event_loop_channel_index) {
248 const Channel *event_loop_channel =
249 event_loop->configuration()->channels()->Get(event_loop_channel_index);
250
251 const Channel *logged_channel = aos::configuration::GetChannel(
252 configuration_, event_loop_channel->name()->string_view(),
253 event_loop_channel->type()->string_view(), "",
254 configuration::GetNode(configuration_, event_loop_->node()));
255
256 if (logged_channel != nullptr) {
257 event_loop_to_logged_channel_index_[event_loop_channel_index] =
258 configuration::ChannelIndex(configuration_, logged_channel);
259 }
260 }
Brian Silverman1f345222020-09-24 21:14:48 -0700261}
262
263Logger::~Logger() {
264 if (log_namer_) {
265 // If we are replaying a log file, or in simulation, we want to force the
266 // last bit of data to be logged. The easiest way to deal with this is to
267 // poll everything as we go to destroy the class, ie, shut down the logger,
268 // and write it to disk.
269 StopLogging(event_loop_->monotonic_now());
270 }
271}
272
Brian Silvermanae7c0332020-09-30 16:58:23 -0700273void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
274 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700275 CHECK(!log_namer_) << ": Already logging";
276 log_namer_ = std::move(log_namer);
Brian Silvermanae7c0332020-09-30 16:58:23 -0700277 log_event_uuid_ = UUID::Random();
278 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700279 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
280
281 // We want to do as much work as possible before the initial Fetch. Time
282 // between that and actually starting to log opens up the possibility of
283 // falling off the end of the queue during that time.
284
285 for (FetcherStruct &f : fetchers_) {
286 if (f.wants_writer) {
287 f.writer = log_namer_->MakeWriter(f.channel);
288 }
289 if (f.wants_timestamp_writer) {
290 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
291 }
292 if (f.wants_contents_writer) {
293 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
294 f.channel, CHECK_NOTNULL(f.timestamp_node));
295 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800296 }
297
Brian Silverman1f345222020-09-24 21:14:48 -0700298 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700299 node_state_.resize(configuration::MultiNode(configuration_)
300 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700301 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800302
Austin Schuh2f8fd752020-09-01 22:38:28 -0700303 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700304 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800305
Austin Schuh2f8fd752020-09-01 22:38:28 -0700306 node_state_[node_index].log_file_header = MakeHeader(node);
307 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800308
Austin Schuh2f8fd752020-09-01 22:38:28 -0700309 // Grab data from each channel right before we declare the log file started
310 // so we can capture the latest message on each channel. This lets us have
311 // non periodic messages with configuration that now get logged.
312 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700313 const auto start = event_loop_->monotonic_now();
314 const bool got_new = f.fetcher->Fetch();
315 const auto end = event_loop_->monotonic_now();
316 RecordFetchResult(start, end, got_new, &f);
317
318 // If there is a message, we want to write it.
319 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 }
321
322 // Clear out any old timestamps in case we are re-starting logging.
323 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800324 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
325 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700326 }
327
328 WriteHeader();
329
330 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
331 << " start_time " << last_synchronized_time_;
332
Austin Schuh315b96b2020-12-11 21:21:12 -0800333 // Force logging up until the start of the log file now, so the messages at
334 // the start are always ordered before the rest of the messages.
335 // Note: this ship may have already sailed, but we don't have to make it
336 // worse.
337 // TODO(austin): Test...
338 LogUntil(last_synchronized_time_);
339
Austin Schuh2f8fd752020-09-01 22:38:28 -0700340 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
341 polling_period_);
342}
343
Brian Silverman1f345222020-09-24 21:14:48 -0700344std::unique_ptr<LogNamer> Logger::StopLogging(
345 aos::monotonic_clock::time_point end_time) {
346 CHECK(log_namer_) << ": Not logging right now";
347
348 if (end_time != aos::monotonic_clock::min_time) {
349 LogUntil(end_time);
350 }
351 timer_handler_->Disable();
352
353 for (FetcherStruct &f : fetchers_) {
354 f.writer = nullptr;
355 f.timestamp_writer = nullptr;
356 f.contents_writer = nullptr;
357 }
358 node_state_.clear();
359
Brian Silvermanae7c0332020-09-30 16:58:23 -0700360 log_event_uuid_ = UUID::Zero();
361 log_start_uuid_ = std::string();
362
Brian Silverman1f345222020-09-24 21:14:48 -0700363 return std::move(log_namer_);
364}
365
Austin Schuhfa895892020-01-07 20:07:41 -0800366void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700367 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700368 server_statistics_fetcher_.Fetch();
369 }
370
371 aos::monotonic_clock::time_point monotonic_start_time =
372 event_loop_->monotonic_now();
373 aos::realtime_clock::time_point realtime_start_time =
374 event_loop_->realtime_now();
375
376 // We need to pick a point in time to declare the log file "started". This
377 // starts here. It needs to be after everything is fetched so that the
378 // fetchers are all pointed at the most recent message before the start
379 // time.
380 last_synchronized_time_ = monotonic_start_time;
381
Austin Schuh6f3babe2020-01-26 20:34:50 -0800382 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700383 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700384 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
385 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800386 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800387 }
388}
Austin Schuh8bd96322020-02-13 21:18:22 -0800389
Austin Schuh315b96b2020-12-11 21:21:12 -0800390void Logger::MaybeWriteHeader(int node_index) {
391 if (configuration::MultiNode(configuration_)) {
392 return MaybeWriteHeader(node_index,
393 configuration_->nodes()->Get(node_index));
394 } else {
395 return MaybeWriteHeader(node_index, nullptr);
396 }
397}
398
399void Logger::MaybeWriteHeader(int node_index, const Node *node) {
400 // This function is responsible for writing the header when the header both
401 // has valid data, and when it needs to be written.
402 if (node_state_[node_index].header_written &&
403 node_state_[node_index].header_valid) {
404 // The header has been written and is valid, nothing to do.
405 return;
406 }
407 if (!node_state_[node_index].has_source_node_boot_uuid) {
408 // Can't write a header if we don't have the boot UUID.
409 return;
410 }
411
412 // WriteHeader writes the first header in a log file. We want to do this only
413 // once.
414 //
415 // Rotate rewrites the same header with a new part ID, but keeps the same part
416 // UUID. We don't want that when things reboot, because that implies that
417 // parts go together across a reboot.
418 //
419 // Reboot resets the parts UUID. So, once we've written a header the first
420 // time, we want to use Reboot to rotate the log and reset the parts UUID.
421 //
422 // header_valid is cleared whenever the remote reboots.
423 if (node_state_[node_index].header_written) {
424 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
425 } else {
426 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
427
428 node_state_[node_index].header_written = true;
429 }
430 node_state_[node_index].header_valid = true;
431}
432
Austin Schuh2f8fd752020-09-01 22:38:28 -0700433void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700434 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700435 server_statistics_fetcher_.Fetch();
436 } else {
437 return;
438 }
439
440 if (server_statistics_fetcher_.get() == nullptr) {
441 return;
442 }
443
444 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700445 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700446 if (MaybeUpdateTimestamp(
447 node, node_index,
448 server_statistics_fetcher_.context().monotonic_event_time,
449 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800450 CHECK(node_state_[node_index].header_written);
451 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700452 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800453 } else {
454 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700455 }
456 }
457}
458
Austin Schuh315b96b2020-12-11 21:21:12 -0800459void Logger::SetStartTime(
460 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
461 aos::realtime_clock::time_point realtime_start_time,
462 aos::monotonic_clock::time_point logger_monotonic_start_time,
463 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700464 node_state_[node_index].monotonic_start_time = monotonic_start_time;
465 node_state_[node_index].realtime_start_time = realtime_start_time;
466 node_state_[node_index]
467 .log_file_header.mutable_message()
468 ->mutate_monotonic_start_time(
469 std::chrono::duration_cast<std::chrono::nanoseconds>(
470 monotonic_start_time.time_since_epoch())
471 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800472
473 // Add logger start times if they are available in the log file header.
474 if (node_state_[node_index]
475 .log_file_header.mutable_message()
476 ->has_logger_monotonic_start_time()) {
477 node_state_[node_index]
478 .log_file_header.mutable_message()
479 ->mutate_logger_monotonic_start_time(
480 std::chrono::duration_cast<std::chrono::nanoseconds>(
481 logger_monotonic_start_time.time_since_epoch())
482 .count());
483 }
484
485 if (node_state_[node_index]
486 .log_file_header.mutable_message()
487 ->has_logger_realtime_start_time()) {
488 node_state_[node_index]
489 .log_file_header.mutable_message()
490 ->mutate_logger_realtime_start_time(
491 std::chrono::duration_cast<std::chrono::nanoseconds>(
492 logger_realtime_start_time.time_since_epoch())
493 .count());
494 }
495
Austin Schuh2f8fd752020-09-01 22:38:28 -0700496 if (node_state_[node_index]
497 .log_file_header.mutable_message()
498 ->has_realtime_start_time()) {
499 node_state_[node_index]
500 .log_file_header.mutable_message()
501 ->mutate_realtime_start_time(
502 std::chrono::duration_cast<std::chrono::nanoseconds>(
503 realtime_start_time.time_since_epoch())
504 .count());
505 }
506}
507
508bool Logger::MaybeUpdateTimestamp(
509 const Node *node, int node_index,
510 aos::monotonic_clock::time_point monotonic_start_time,
511 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700512 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700513 if (node_state_[node_index].monotonic_start_time !=
514 monotonic_clock::min_time) {
515 return false;
516 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800517 if (event_loop_->node() == node ||
518 !configuration::MultiNode(configuration_)) {
519 // There are no offsets to compute for ourself, so always succeed.
520 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
521 monotonic_start_time, realtime_start_time);
522 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700523 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800524 } else if (server_statistics_fetcher_.get() != nullptr) {
525 // We must be a remote node now. Look for the connection and see if it is
526 // connected.
527
528 for (const message_bridge::ServerConnection *connection :
529 *server_statistics_fetcher_->connections()) {
530 if (connection->node()->name()->string_view() !=
531 node->name()->string_view()) {
532 continue;
533 }
534
535 if (connection->state() != message_bridge::State::CONNECTED) {
536 VLOG(1) << node->name()->string_view()
537 << " is not connected, can't start it yet.";
538 break;
539 }
540
541 // Update the boot UUID as soon as we know we are connected.
542 if (!connection->has_boot_uuid()) {
543 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
544 break;
545 }
546
547 if (!node_state_[node_index].has_source_node_boot_uuid ||
548 node_state_[node_index].source_node_boot_uuid !=
549 connection->boot_uuid()->string_view()) {
550 node_state_[node_index].SetBootUUID(
551 connection->boot_uuid()->string_view());
552 }
553
554 if (!connection->has_monotonic_offset()) {
555 VLOG(1) << "Missing monotonic offset for setting start time for node "
556 << aos::FlatbufferToJson(node);
557 break;
558 }
559
560 // Found it and it is connected. Compensate and go.
561 SetStartTime(node_index,
562 monotonic_start_time +
563 std::chrono::nanoseconds(connection->monotonic_offset()),
564 realtime_start_time, monotonic_start_time,
565 realtime_start_time);
566 return true;
567 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700568 }
569 return false;
570}
571
572aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
573 const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800574 // Now write the header with this timestamp in it.
575 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800576 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800577
Austin Schuh2f8fd752020-09-01 22:38:28 -0700578 // TODO(austin): Compress this much more efficiently. There are a bunch of
579 // duplicated schemas.
Brian Silvermanae7c0332020-09-30 16:58:23 -0700580 const flatbuffers::Offset<aos::Configuration> configuration_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700581 CopyFlatBuffer(configuration_, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800582
Brian Silvermanae7c0332020-09-30 16:58:23 -0700583 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700584 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800585
Brian Silvermanae7c0332020-09-30 16:58:23 -0700586 CHECK(log_event_uuid_ != UUID::Zero());
587 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
588 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700589
Brian Silvermanae7c0332020-09-30 16:58:23 -0700590 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
591 fbb.CreateString(logger_instance_uuid_.string_view());
592
593 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
594 if (!log_start_uuid_.empty()) {
595 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
596 }
597
Austin Schuh315b96b2020-12-11 21:21:12 -0800598 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
599 fbb.CreateString(event_loop_->boot_uuid().string_view());
600
601 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
602 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700603
604 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700605 fbb.CreateString("00000000-0000-4000-8000-000000000000");
606
Austin Schuhfa895892020-01-07 20:07:41 -0800607 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700608 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700609
Austin Schuh0c297012020-09-16 18:41:59 -0700610 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800611 // TODO(austin): Reuse the node we just copied in above.
612 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
613 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800614 }
615
616 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
617
Austin Schuh64fab802020-09-09 22:47:47 -0700618 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800619
620 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800621 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800622 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700623 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800624 }
625
626 log_file_header_builder.add_configuration(configuration_offset);
627 // The worst case theoretical out of order is the polling period times 2.
628 // One message could get logged right after the boundary, but be for right
629 // before the next boundary. And the reverse could happen for another
630 // message. Report back 3x to be extra safe, and because the cost isn't
631 // huge on the read side.
632 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700633 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800634
635 log_file_header_builder.add_monotonic_start_time(
636 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700637 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800638 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700639 if (node == event_loop_->node()) {
640 log_file_header_builder.add_realtime_start_time(
641 std::chrono::duration_cast<std::chrono::nanoseconds>(
642 realtime_clock::min_time.time_since_epoch())
643 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800644 } else {
645 log_file_header_builder.add_logger_monotonic_start_time(
646 std::chrono::duration_cast<std::chrono::nanoseconds>(
647 monotonic_clock::min_time.time_since_epoch())
648 .count());
649 log_file_header_builder.add_logger_realtime_start_time(
650 std::chrono::duration_cast<std::chrono::nanoseconds>(
651 realtime_clock::min_time.time_since_epoch())
652 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800653 }
654
Brian Silvermanae7c0332020-09-30 16:58:23 -0700655 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
656 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
657 if (!log_start_uuid_offset.IsNull()) {
658 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
659 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800660 log_file_header_builder.add_logger_node_boot_uuid(
661 logger_node_boot_uuid_offset);
662 log_file_header_builder.add_source_node_boot_uuid(
663 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700664
665 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
666 log_file_header_builder.add_parts_index(0);
667
Austin Schuh2f8fd752020-09-01 22:38:28 -0700668 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800669 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
670 fbb.Release());
671
672 CHECK(result.Verify()) << ": Built a corrupted header.";
673
674 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700675}
676
Brian Silvermancb805822020-10-06 17:43:35 -0700677void Logger::ResetStatisics() {
678 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
679 max_message_fetch_time_channel_ = -1;
680 max_message_fetch_time_size_ = -1;
681 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
682 total_message_fetch_count_ = 0;
683 total_message_fetch_bytes_ = 0;
684 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
685 total_nop_fetch_count_ = 0;
686 max_copy_time_ = std::chrono::nanoseconds::zero();
687 max_copy_time_channel_ = -1;
688 max_copy_time_size_ = -1;
689 total_copy_time_ = std::chrono::nanoseconds::zero();
690 total_copy_count_ = 0;
691 total_copy_bytes_ = 0;
692}
693
Austin Schuh2f8fd752020-09-01 22:38:28 -0700694void Logger::Rotate() {
695 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700696 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700697 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700698 }
699}
700
701void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800702 // Grab the latest ServerStatistics message. This will always have the
703 // oppertunity to be >= to the current time, so it will always represent any
704 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700705 WriteMissingTimestamps();
706
707 // Write each channel to disk, one at a time.
708 for (FetcherStruct &f : fetchers_) {
709 while (true) {
710 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700711 const auto start = event_loop_->monotonic_now();
712 const bool got_new = f.fetcher->FetchNext();
713 const auto end = event_loop_->monotonic_now();
714 RecordFetchResult(start, end, got_new, &f);
715 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700716 VLOG(2) << "No new data on "
717 << configuration::CleanedChannelToString(
718 f.fetcher->channel());
719 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720 }
Brian Silvermancb805822020-10-06 17:43:35 -0700721 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700722 }
723
Austin Schuh2f8fd752020-09-01 22:38:28 -0700724 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700725 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700726 break;
727 }
Brian Silvermancb805822020-10-06 17:43:35 -0700728 if (f.writer != nullptr) {
729 // Write!
730 const auto start = event_loop_->monotonic_now();
731 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
732 max_header_size_);
733 fbb.ForceDefaults(true);
734
735 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
736 f.channel_index, f.log_type));
737 const auto end = event_loop_->monotonic_now();
738 RecordCreateMessageTime(start, end, &f);
739
740 VLOG(2) << "Writing data as node "
741 << FlatbufferToJson(event_loop_->node()) << " for channel "
742 << configuration::CleanedChannelToString(f.fetcher->channel())
743 << " to " << f.writer->filename() << " data "
744 << FlatbufferToJson(
745 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
746 fbb.GetBufferPointer()));
747
748 max_header_size_ = std::max(max_header_size_,
749 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800750 CHECK(node_state_[f.data_node_index].header_valid)
751 << ": Can't write data before the header on channel "
752 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700753 f.writer->QueueSizedFlatbuffer(&fbb);
754 }
755
756 if (f.timestamp_writer != nullptr) {
757 // And now handle timestamps.
758 const auto start = event_loop_->monotonic_now();
759 flatbuffers::FlatBufferBuilder fbb;
760 fbb.ForceDefaults(true);
761
762 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
763 f.channel_index,
764 LogType::kLogDeliveryTimeOnly));
765 const auto end = event_loop_->monotonic_now();
766 RecordCreateMessageTime(start, end, &f);
767
768 VLOG(2) << "Writing timestamps as node "
769 << FlatbufferToJson(event_loop_->node()) << " for channel "
770 << configuration::CleanedChannelToString(f.fetcher->channel())
771 << " to " << f.timestamp_writer->filename() << " timestamp "
772 << FlatbufferToJson(
773 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
774 fbb.GetBufferPointer()));
775
Austin Schuh315b96b2020-12-11 21:21:12 -0800776 CHECK(node_state_[f.timestamp_node_index].header_valid)
777 << ": Can't write data before the header on channel "
778 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700779 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
780 }
781
782 if (f.contents_writer != nullptr) {
783 const auto start = event_loop_->monotonic_now();
784 // And now handle the special message contents channel. Copy the
785 // message into a FlatBufferBuilder and save it to disk.
786 // TODO(austin): We can be more efficient here when we start to
787 // care...
788 flatbuffers::FlatBufferBuilder fbb;
789 fbb.ForceDefaults(true);
790
Austin Schuh0de30f32020-12-06 12:44:28 -0800791 const RemoteMessage *msg =
792 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700793
Austin Schuh315b96b2020-12-11 21:21:12 -0800794 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
795 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
796 node_state_[f.contents_node_index].source_node_boot_uuid !=
797 msg->boot_uuid()->string_view()) {
798 node_state_[f.contents_node_index].SetBootUUID(
799 msg->boot_uuid()->string_view());
800
801 MaybeWriteHeader(f.contents_node_index);
802 }
803
Brian Silvermancb805822020-10-06 17:43:35 -0700804 logger::MessageHeader::Builder message_header_builder(fbb);
805
806 // TODO(austin): This needs to check the channel_index and confirm
807 // that it should be logged before squirreling away the timestamp to
808 // disk. We don't want to log irrelevant timestamps.
809
810 // Note: this must match the same order as MessageBridgeServer and
811 // PackMessage. We want identical headers to have identical
812 // on-the-wire formats to make comparing them easier.
813
814 // Translate from the channel index that the event loop uses to the
815 // channel index in the log file.
816 message_header_builder.add_channel_index(
817 event_loop_to_logged_channel_index_[msg->channel_index()]);
818
819 message_header_builder.add_queue_index(msg->queue_index());
820 message_header_builder.add_monotonic_sent_time(
821 msg->monotonic_sent_time());
822 message_header_builder.add_realtime_sent_time(
823 msg->realtime_sent_time());
824
825 message_header_builder.add_monotonic_remote_time(
826 msg->monotonic_remote_time());
827 message_header_builder.add_realtime_remote_time(
828 msg->realtime_remote_time());
829 message_header_builder.add_remote_queue_index(
830 msg->remote_queue_index());
831
832 fbb.FinishSizePrefixed(message_header_builder.Finish());
833 const auto end = event_loop_->monotonic_now();
834 RecordCreateMessageTime(start, end, &f);
835
Austin Schuh315b96b2020-12-11 21:21:12 -0800836 CHECK(node_state_[f.contents_node_index].header_valid)
837 << ": Can't write data before the header on channel "
838 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700839 f.contents_writer->QueueSizedFlatbuffer(&fbb);
840 }
841
842 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700843 }
844 }
845 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800846}
847
Brian Silverman1f345222020-09-24 21:14:48 -0700848void Logger::DoLogData(const monotonic_clock::time_point end_time) {
849 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800850 // max_out_of_order_duration. To do this, we need sync points. Every write
851 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800852
853 do {
854 // Move the sync point up by at most polling_period. This forces one sync
855 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700856 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
857
858 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800859
Austin Schuhe309d2a2019-11-29 13:25:21 -0800860 // If we missed cycles, we could be pretty far behind. Spin until we are
861 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700862 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800863}
864
Brian Silvermancb805822020-10-06 17:43:35 -0700865void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
866 aos::monotonic_clock::time_point end,
867 bool got_new, FetcherStruct *fetcher) {
868 const auto duration = end - start;
869 if (!got_new) {
870 ++total_nop_fetch_count_;
871 total_nop_fetch_time_ += duration;
872 return;
873 }
874 ++total_message_fetch_count_;
875 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
876 total_message_fetch_time_ += duration;
877 if (duration > max_message_fetch_time_) {
878 max_message_fetch_time_ = duration;
879 max_message_fetch_time_channel_ = fetcher->channel_index;
880 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
881 }
882}
883
884void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
885 aos::monotonic_clock::time_point end,
886 FetcherStruct *fetcher) {
887 const auto duration = end - start;
888 total_copy_time_ += duration;
889 ++total_copy_count_;
890 total_copy_bytes_ += fetcher->fetcher->context().size;
891 if (duration > max_copy_time_) {
892 max_copy_time_ = duration;
893 max_copy_time_channel_ = fetcher->channel_index;
894 max_copy_time_size_ = fetcher->fetcher->context().size;
895 }
896}
897
Austin Schuh11d43732020-09-21 17:28:30 -0700898std::vector<std::vector<std::string>> ToLogReaderVector(
899 const std::vector<LogFile> &log_files) {
900 std::vector<std::vector<std::string>> result;
901 for (const LogFile &log_file : log_files) {
902 for (const LogParts &log_parts : log_file.parts) {
903 std::vector<std::string> parts;
904 for (const std::string &part : log_parts.parts) {
905 parts.emplace_back(part);
906 }
907 result.emplace_back(std::move(parts));
908 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700909 }
910 return result;
911}
912
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800913LogReader::LogReader(std::string_view filename,
914 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800915 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800916
Austin Schuh287d43d2020-12-04 20:19:33 -0800917LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800918 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800919 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800920 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800921 CHECK_GT(log_files_.size(), 0u);
922 {
923 // Validate that we have the same config everwhere. This will be true if
924 // all the parts were sorted together and the configs match.
925 const Configuration *config = nullptr;
926 for (const LogFile &log_file : log_files) {
927 if (config == nullptr) {
928 config = log_file.config.get();
929 } else {
930 CHECK_EQ(config, log_file.config.get());
931 }
932 }
933 }
Austin Schuh6331ef92020-01-07 18:28:09 -0800934 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800935
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700936 // Remap all existing remote timestamp channels. They will be recreated, and
937 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700938 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700939 std::vector<const Node *> timestamp_logger_nodes =
940 configuration::TimestampNodes(logged_configuration(), node);
941 for (const Node *remote_node : timestamp_logger_nodes) {
942 const std::string channel = absl::StrCat(
943 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800944 // See if the log file is an old log with MessageHeader channels in it, or
945 // a newer log with RemoteMessage. If we find an older log, rename the
946 // type too along with the name.
947 if (HasChannel<MessageHeader>(channel, node)) {
948 CHECK(!HasChannel<RemoteMessage>(channel, node))
949 << ": Can't have both a MessageHeader and RemoteMessage remote "
950 "timestamp channel.";
951 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
952 "aos.message_bridge.RemoteMessage");
953 } else {
954 CHECK(HasChannel<RemoteMessage>(channel, node))
955 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
956 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
957 << node->name()->string_view();
958 RemapLoggedChannel<RemoteMessage>(channel, node);
959 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700960 }
961 }
962
Austin Schuh6aa77be2020-02-22 21:06:40 -0800963 if (replay_configuration) {
964 CHECK_EQ(configuration::MultiNode(configuration()),
965 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -0700966 << ": Log file and replay config need to both be multi or single "
967 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -0800968 }
969
Austin Schuh6f3babe2020-01-26 20:34:50 -0800970 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -0800971 states_.emplace_back(std::make_unique<State>(
972 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -0800973 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800974 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700975 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800976 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -0700977 << ": Log file and replay config need to have matching nodes "
978 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700979 for (const Node *node : *logged_configuration()->nodes()) {
980 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700981 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
982 << " in logged config that is not present in the replay "
983 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700984 }
985 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800986 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800987 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800988 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800989}
990
Austin Schuh6aa77be2020-02-22 21:06:40 -0800991LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -0700992 if (event_loop_factory_unique_ptr_) {
993 Deregister();
994 } else if (event_loop_factory_ != nullptr) {
995 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
996 "is destroyed";
997 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700998 // Zero out some buffers. It's easy to do use-after-frees on these, so make
999 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001000 if (remapped_configuration_buffer_) {
1001 remapped_configuration_buffer_->Wipe();
1002 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001003}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001004
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001005const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001006 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001007}
1008
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001009const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001010 return remapped_configuration_;
1011}
1012
Austin Schuh6f3babe2020-01-26 20:34:50 -08001013std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001014 // Because the Node pointer will only be valid if it actually points to
1015 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001016 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001017 //
1018 // Also, note, that when ever a map is changed, the nodes in here are
1019 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001020 CHECK(remapped_configuration_ != nullptr)
1021 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001022 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001023}
Austin Schuh15649d62019-12-28 16:36:38 -08001024
Austin Schuh11d43732020-09-21 17:28:30 -07001025monotonic_clock::time_point LogReader::monotonic_start_time(
1026 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001027 State *state =
1028 states_[configuration::GetNodeIndex(configuration(), node)].get();
1029 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1030
Austin Schuh858c9f32020-08-31 16:56:12 -07001031 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001032}
1033
Austin Schuh11d43732020-09-21 17:28:30 -07001034realtime_clock::time_point LogReader::realtime_start_time(
1035 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001036 State *state =
1037 states_[configuration::GetNodeIndex(configuration(), node)].get();
1038 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1039
Austin Schuh858c9f32020-08-31 16:56:12 -07001040 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001041}
1042
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001043void LogReader::Register() {
1044 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001045 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001046 Register(event_loop_factory_unique_ptr_.get());
1047}
1048
Austin Schuh92547522019-12-28 14:33:43 -08001049void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001050 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001051 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001052 filters_ =
1053 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
1054 event_loop_factory_);
Austin Schuh92547522019-12-28 14:33:43 -08001055
Brian Silvermand90905f2020-09-23 14:42:56 -07001056 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001057 const size_t node_index =
1058 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001059 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1060 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001061
1062 // Confirm that all the parts are from the same boot if there are enough
1063 // parts to not be from the same boot.
1064 if (filtered_parts.size() > 1u) {
1065 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1066 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1067 filtered_parts[0].source_boot_uuid)
1068 << ": Found parts from different boots "
1069 << LogFileVectorToString(log_files_);
1070 }
1071 }
1072
Austin Schuh287d43d2020-12-04 20:19:33 -08001073 states_[node_index] = std::make_unique<State>(
1074 filtered_parts.size() == 0u
1075 ? nullptr
1076 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001077 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001078 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001079 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001080
1081 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001082 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001083
Austin Schuh287d43d2020-12-04 20:19:33 -08001084 for (const Node *node : configuration::GetNodes(configuration())) {
1085 const size_t node_index =
1086 configuration::GetNodeIndex(configuration(), node);
1087 State *state = states_[node_index].get();
1088 for (const Node *other_node : configuration::GetNodes(configuration())) {
1089 const size_t other_node_index =
1090 configuration::GetNodeIndex(configuration(), other_node);
1091 State *other_state = states_[other_node_index].get();
1092 if (other_state != state) {
1093 state->AddPeer(other_state);
1094 }
1095 }
1096 }
1097
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001098 // Register after making all the State objects so we can build references
1099 // between them.
1100 for (const Node *node : configuration::GetNodes(configuration())) {
1101 const size_t node_index =
1102 configuration::GetNodeIndex(configuration(), node);
1103 State *state = states_[node_index].get();
1104
1105 Register(state->event_loop());
1106 }
1107
James Kuszmaul46d82582020-05-09 19:50:09 -07001108 if (live_nodes_ == 0) {
1109 LOG(FATAL)
1110 << "Don't have logs from any of the nodes in the replay config--are "
1111 "you sure that the replay config matches the original config?";
1112 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001113
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001114 filters_->Initialize(logged_configuration());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001115
Austin Schuh858c9f32020-08-31 16:56:12 -07001116 for (std::unique_ptr<State> &state : states_) {
1117 state->SeedSortedMessages();
1118 }
1119
Austin Schuh2f8fd752020-09-01 22:38:28 -07001120 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001121 UpdateOffsets();
1122
Austin Schuh2f8fd752020-09-01 22:38:28 -07001123 // We want to start the log file at the last start time of the log files
1124 // from all the nodes. Compute how long each node's simulation needs to run
1125 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001126 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001127
Austin Schuh2f8fd752020-09-01 22:38:28 -07001128 // TODO(austin): We want an "OnStart" callback for each node rather than
1129 // running until the last node.
1130
Austin Schuh8bd96322020-02-13 21:18:22 -08001131 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001132 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1133 << MaybeNodeName(state->event_loop()->node()) << "now "
1134 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001135 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1136 continue;
1137 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001138 // And start computing the start time on the distributed clock now that
1139 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001140 start_time = std::max(
1141 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001142 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001143
1144 CHECK_GE(start_time, distributed_clock::epoch())
1145 << ": Hmm, we have a node starting before the start of time. Offset "
1146 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001147
Austin Schuh6f3babe2020-01-26 20:34:50 -08001148 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1149 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001150 // nodes, and also replayed on the other nodes. This may not satisfy all
1151 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001152 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1153 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1154 const Channel *channel = logged_configuration()->channels()->Get(i);
1155 const Node *node = configuration::GetNode(
1156 configuration(), channel->source_node()->string_view());
1157
Austin Schuh8bd96322020-02-13 21:18:22 -08001158 State *state =
1159 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001160
1161 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001162 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001163
1164 event_loop_factory_->DisableForwarding(remapped_channel);
1165 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001166
1167 // If we are replaying a log, we don't want a bunch of redundant messages
1168 // from both the real message bridge and simulated message bridge.
1169 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001170 }
1171
Austin Schuhcde938c2020-02-02 17:30:07 -08001172 // While we are starting the system up, we might be relying on matching data
1173 // to timestamps on log files where the timestamp log file starts before the
1174 // data. In this case, it is reasonable to expect missing data.
1175 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001176 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001177 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001178 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001179 // Now that we are running for real, missing data means that the log file is
1180 // corrupted or went wrong.
1181 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001182
Austin Schuh8bd96322020-02-13 21:18:22 -08001183 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001184 // Make the RT clock be correct before handing it to the user.
1185 if (state->realtime_start_time() != realtime_clock::min_time) {
1186 state->SetRealtimeOffset(state->monotonic_start_time(),
1187 state->realtime_start_time());
1188 }
1189 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1190 << MaybeNodeName(state->event_loop()->node()) << "now "
1191 << state->monotonic_now();
1192 }
1193
1194 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001195 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -08001196 }
1197}
1198
Austin Schuh2f8fd752020-09-01 22:38:28 -07001199void LogReader::UpdateOffsets() {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001200 filters_->UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001201
1202 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001203 filters_->LogFit("Offset is");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001204 }
1205}
1206
1207message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001208 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001209 if (filters_) {
1210 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001211 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001212 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001213}
1214
Austin Schuhe309d2a2019-11-29 13:25:21 -08001215void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001216 State *state =
1217 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1218 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001219
Austin Schuh858c9f32020-08-31 16:56:12 -07001220 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001221
Tyler Chatow67ddb032020-01-12 14:30:04 -08001222 // We don't run timing reports when trying to print out logged data, because
1223 // otherwise we would end up printing out the timing reports themselves...
1224 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225 event_loop->SkipTimingReport();
1226 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001227
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001228 for (size_t logged_channel_index = 0;
1229 logged_channel_index < logged_configuration()->channels()->size();
1230 ++logged_channel_index) {
1231 const Channel *channel = RemapChannel(
1232 event_loop,
1233 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001234
Austin Schuh2f8fd752020-09-01 22:38:28 -07001235 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh0de30f32020-12-06 12:44:28 -08001236 aos::Sender<RemoteMessage> *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001237
1238 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001239
1240 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1241 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001242 // We've got a message which is being forwarded to this node.
1243 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001244 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001245 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001246
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001247 // Delivery timestamps are supposed to be logged back on the source node.
1248 // Configure remote timestamps to be sent.
1249 const bool delivery_time_is_logged =
1250 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1251 channel, event_loop->node(), source_node);
1252
1253 source_state =
1254 states_[configuration::GetNodeIndex(configuration(), source_node)]
1255 .get();
1256
1257 if (delivery_time_is_logged) {
1258 remote_timestamp_sender =
1259 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001260 }
1261 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001262
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001263 state->SetChannel(
1264 logged_channel_index,
1265 configuration::ChannelIndex(event_loop->configuration(), channel),
1266 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1267 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001268 }
1269
Austin Schuh6aa77be2020-02-22 21:06:40 -08001270 // If we didn't find any log files with data in them, we won't ever get a
1271 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001272 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001273 return;
1274 }
1275
Austin Schuh858c9f32020-08-31 16:56:12 -07001276 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001277 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1278 << "at " << state->event_loop()->context().monotonic_event_time
1279 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001280 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001281 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001282 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001283 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001284 event_loop_factory_->Exit();
1285 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001286 return;
1287 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001288 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001289 filters_->LogFit("Offset was");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001290 }
1291
1292 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001293 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001294
Austin Schuhe309d2a2019-11-29 13:25:21 -08001295 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001296 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001297 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001298 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001299 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1300 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001301 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001302 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001303 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001304 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001305 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001306 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001307 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001308 << "): " << FlatbufferToJson(state->event_loop()->node())
1309 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001310 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001311 << state->DebugString();
1312 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001313
Austin Schuh287d43d2020-12-04 20:19:33 -08001314 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001315 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001316 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001317 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001318 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001319 timestamped_message.data.span().size() != 0u) {
1320 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001321 << ": Got a message without data on channel "
1322 << configuration::CleanedChannelToString(
1323 logged_configuration()->channels()->Get(
1324 timestamped_message.channel_index))
1325 << ". Forwarding entry which was not matched? Use "
1326 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001327
Austin Schuh2f8fd752020-09-01 22:38:28 -07001328 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001329 // Confirm that the message was sent on the sending node before the
1330 // destination node (this node). As a proxy, do this by making sure
1331 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001332 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001333 CHECK_LT(
1334 timestamped_message.monotonic_remote_time,
1335 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001336 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001337 << state->remote_node(timestamped_message.channel_index)
1338 ->name()
1339 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001340 << " while trying to send a message on "
1341 << configuration::CleanedChannelToString(
1342 logged_configuration()->channels()->Get(
1343 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001344 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001345 } else if (timestamped_message.monotonic_remote_time >=
1346 state->monotonic_remote_now(
1347 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001348 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001349 << "Check failed: timestamped_message.monotonic_remote_time < "
1350 "state->monotonic_remote_now(timestamped_message.channel_"
1351 "index) ("
1352 << timestamped_message.monotonic_remote_time << " vs. "
1353 << state->monotonic_remote_now(
1354 timestamped_message.channel_index)
1355 << ") " << state->event_loop()->node()->name()->string_view()
1356 << " to "
1357 << state->remote_node(timestamped_message.channel_index)
1358 ->name()
1359 ->string_view()
1360 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 << " ("
1362 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001363 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001364 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001365 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001366 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001367 timestamped_message.channel_index,
1368 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001369 << ") " << state->DebugString();
1370 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001371 }
1372
Austin Schuh15649d62019-12-28 16:36:38 -08001373 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001374 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1375 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001376
Austin Schuh2f8fd752020-09-01 22:38:28 -07001377 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001378 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001379 // TODO(austin): std::move channel_data in and make that efficient in
1380 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001381 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001382 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001383 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001384 // reading the rest of the log file and call it quits. We don't want
1385 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001386 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1387 bool update_time_dummy;
1388 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001389 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001390 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001391 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001392 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001393 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001394 LOG(WARNING)
1395 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001396 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001397 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001398 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001399 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001400 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001401 }
1402
Austin Schuh858c9f32020-08-31 16:56:12 -07001403 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001404 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001405 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1406 << "wakeup for " << next_time << "("
1407 << state->ToDistributedClock(next_time)
1408 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001409 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001410 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001411 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1412 << "No next message, scheduling shutdown";
1413 // Set a timer up immediately after now to die. If we don't do this,
1414 // then the senders waiting on the message we just read will never get
1415 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001416 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001417 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1418 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001419 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001420 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001421
Austin Schuh2f8fd752020-09-01 22:38:28 -07001422 // Once we make this call, the current time changes. So do everything
1423 // which involves time before changing it. That especially includes
1424 // sending the message.
1425 if (update_time) {
1426 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1427 << "updating offsets";
1428
1429 std::vector<aos::monotonic_clock::time_point> before_times;
1430 before_times.resize(states_.size());
1431 std::transform(states_.begin(), states_.end(), before_times.begin(),
1432 [](const std::unique_ptr<State> &state) {
1433 return state->monotonic_now();
1434 });
1435
Austin Schuh8bd96322020-02-13 21:18:22 -08001436 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001437 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1438 << state->monotonic_now();
1439
Austin Schuh2f8fd752020-09-01 22:38:28 -07001440 // TODO(austin): We should be perfect.
1441 const std::chrono::nanoseconds kTolerance{3};
1442 if (!FLAGS_skip_order_validation) {
1443 CHECK_GE(next_time, state->monotonic_now())
1444 << ": Time skipped the next event.";
1445
1446 for (size_t i = 0; i < states_.size(); ++i) {
1447 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1448 << ": Time changed too much on node "
1449 << MaybeNodeName(states_[i]->event_loop()->node());
1450 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1451 << ": Time changed too much on node "
Austin Schuhc9049732020-12-21 22:27:15 -08001452 << MaybeNodeName(states_[i]->event_loop()->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001453 }
1454 } else {
1455 if (next_time < state->monotonic_now()) {
1456 LOG(WARNING) << "Check failed: next_time >= "
1457 "state->monotonic_now() ("
1458 << next_time << " vs. " << state->monotonic_now()
1459 << "): Time skipped the next event.";
1460 }
1461 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001462 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001463 LOG(WARNING) << "Check failed: "
1464 "states_[i]->monotonic_now() "
1465 ">= before_times[i] - kTolerance ("
1466 << states_[i]->monotonic_now() << " vs. "
1467 << before_times[i] - kTolerance
1468 << ") : Time changed too much on node "
1469 << MaybeNodeName(states_[i]->event_loop()->node());
1470 }
Austin Schuh724032b2020-12-18 22:54:59 -08001471 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001472 LOG(WARNING) << "Check failed: "
1473 "states_[i]->monotonic_now() "
1474 "<= before_times[i] + kTolerance ("
1475 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001476 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001477 << ") : Time changed too much on node "
1478 << MaybeNodeName(states_[i]->event_loop()->node());
1479 }
1480 }
1481 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001482 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001483
1484 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1485 << state->event_loop()->context().monotonic_event_time << " now "
1486 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001487 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001488
Austin Schuh6f3babe2020-01-26 20:34:50 -08001489 ++live_nodes_;
1490
Austin Schuh858c9f32020-08-31 16:56:12 -07001491 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1492 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001493 }
1494}
1495
1496void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001497 // Make sure that things get destroyed in the correct order, rather than
1498 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001499 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001500 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001501 }
Austin Schuh92547522019-12-28 14:33:43 -08001502
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001503 event_loop_factory_unique_ptr_.reset();
1504 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001505}
1506
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001507void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001508 std::string_view add_prefix,
1509 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001510 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1511 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1512 if (channel->name()->str() == name &&
1513 channel->type()->string_view() == type) {
1514 CHECK_EQ(0u, remapped_channels_.count(ii))
1515 << "Already remapped channel "
1516 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001517 RemappedChannel remapped_channel;
1518 remapped_channel.remapped_name =
1519 std::string(add_prefix) + std::string(name);
1520 remapped_channel.new_type = new_type;
1521 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001522 VLOG(1) << "Remapping channel "
1523 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001524 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001525 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001526 return;
1527 }
1528 }
1529 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1530 << type;
1531}
1532
Austin Schuh01b4c352020-09-21 23:09:39 -07001533void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1534 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001535 std::string_view add_prefix,
1536 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001537 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1538 const Channel *remapped_channel =
1539 configuration::GetChannel(logged_configuration(), name, type, "", node);
1540 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1541 << "\", \"type\": \"" << type << "\"}";
1542 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1543 << "\"}";
1544 VLOG(1) << "Remapped "
1545 << aos::configuration::StrippedChannelToString(remapped_channel);
1546
1547 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1548 // we want it to degrade if the heuristics fail to just work.
1549 //
1550 // The easiest way to do this is going to be incredibly specific and verbose.
1551 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1552 // /original/0/spray. Then, create a map from /original/spray to
1553 // /original/0/spray for just the type we were asked for.
1554 if (name != remapped_channel->name()->string_view()) {
1555 MapT new_map;
1556 new_map.match = std::make_unique<ChannelT>();
1557 new_map.match->name = absl::StrCat(add_prefix, name);
1558 new_map.match->type = type;
1559 if (node != nullptr) {
1560 new_map.match->source_node = node->name()->str();
1561 }
1562 new_map.rename = std::make_unique<ChannelT>();
1563 new_map.rename->name =
1564 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1565 maps_.emplace_back(std::move(new_map));
1566 }
1567
1568 const size_t channel_index =
1569 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1570 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1571 << "Already remapped channel "
1572 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001573
1574 RemappedChannel remapped_channel_struct;
1575 remapped_channel_struct.remapped_name =
1576 std::string(add_prefix) +
1577 std::string(remapped_channel->name()->string_view());
1578 remapped_channel_struct.new_type = new_type;
1579 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001580 MakeRemappedConfig();
1581}
1582
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001583void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001584 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001585 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001586 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001587 << ": Can't change the mapping after the events are scheduled.";
1588 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001589 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001590
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001591 // If no remapping occurred and we are using the original config, then there
1592 // is nothing interesting to do here.
1593 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001594 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001595 return;
1596 }
1597 // Config to copy Channel definitions from. Use the specified
1598 // replay_configuration_ if it has been provided.
1599 const Configuration *const base_config = replay_configuration_ == nullptr
1600 ? logged_configuration()
1601 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001602
1603 // Create a config with all the channels, but un-sorted/merged. Collect up
1604 // the schemas while we do this. Call MergeConfiguration to sort everything,
1605 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001606
1607 // This is the builder that we use for the config containing all the new
1608 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001609 flatbuffers::FlatBufferBuilder fbb;
1610 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001611 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001612
1613 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1614 << ": Merging logic needs to be updated when the number of channel "
1615 "fields changes.";
1616
1617 // List of schemas.
1618 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1619 // Make sure our new RemoteMessage schema is in there for old logs without it.
1620 schema_map.insert(std::make_pair(
1621 RemoteMessage::GetFullyQualifiedName(),
1622 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1623 message_bridge::RemoteMessageSchema()))));
1624
1625 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001626 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001627 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001628 base_config, logged_configuration()->channels()->Get(pair.first), "",
1629 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001630 channel_offsets.emplace_back(
1631 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001632 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001633
Austin Schuh0de30f32020-12-06 12:44:28 -08001634 // Now reconstruct the original channels, translating types as needed
1635 for (const Channel *c : *base_config->channels()) {
1636 // Search for a mapping channel.
1637 std::string_view new_type = "";
1638 for (auto &pair : remapped_channels_) {
1639 const Channel *const remapped_channel =
1640 logged_configuration()->channels()->Get(pair.first);
1641 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1642 remapped_channel->type()->string_view() == c->type()->string_view()) {
1643 new_type = pair.second.new_type;
1644 break;
1645 }
1646 }
1647
1648 // Copy everything over.
1649 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1650
1651 // Add the schema if it doesn't exist.
1652 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1653 CHECK(c->has_schema());
1654 schema_map.insert(std::make_pair(c->type()->string_view(),
1655 RecursiveCopyFlatBuffer(c->schema())));
1656 }
1657 }
1658
1659 // The MergeConfiguration API takes a vector, not a map. Convert.
1660 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1661 while (!schema_map.empty()) {
1662 schemas.emplace_back(std::move(schema_map.begin()->second));
1663 schema_map.erase(schema_map.begin());
1664 }
1665
1666 // Create the Configuration containing the new channels that we want to add.
1667 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1668 channels_offset =
1669 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1670
1671 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001672 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001673 if (base_config->maps()) {
1674 for (const Map *map : *base_config->maps()) {
1675 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1676 }
1677 }
1678
1679 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001680 for (const MapT &map : maps_) {
1681 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001682 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001683 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001684 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001685 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001686 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001687 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1688 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001689 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001690 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001691 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001692 match_builder.add_name(match_name_offset);
1693 match_builder.add_type(match_type_offset);
1694 if (!map.match->source_node.empty()) {
1695 match_builder.add_source_node(match_source_node_offset);
1696 }
1697 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1698
Austin Schuh0de30f32020-12-06 12:44:28 -08001699 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001700 rename_builder.add_name(rename_name_offset);
1701 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1702
Austin Schuh0de30f32020-12-06 12:44:28 -08001703 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001704 map_builder.add_match(match_offset);
1705 map_builder.add_rename(rename_offset);
1706 map_offsets.emplace_back(map_builder.Finish());
1707 }
1708
Austin Schuh0de30f32020-12-06 12:44:28 -08001709 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1710 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001711
Austin Schuh0de30f32020-12-06 12:44:28 -08001712 // And copy everything else over.
1713 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1714 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1715
1716 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1717 applications_offset =
1718 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1719
1720 // Now insert everything else in unmodified.
1721 ConfigurationBuilder configuration_builder(fbb);
1722 if (!channels_offset.IsNull()) {
1723 configuration_builder.add_channels(channels_offset);
1724 }
1725 if (!maps_offsets.IsNull()) {
1726 configuration_builder.add_maps(maps_offsets);
1727 }
1728 if (!nodes_offset.IsNull()) {
1729 configuration_builder.add_nodes(nodes_offset);
1730 }
1731 if (!applications_offset.IsNull()) {
1732 configuration_builder.add_applications(applications_offset);
1733 }
1734
1735 if (base_config->has_channel_storage_duration()) {
1736 configuration_builder.add_channel_storage_duration(
1737 base_config->channel_storage_duration());
1738 }
1739
1740 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1741 << ": Merging logic needs to be updated when the number of configuration "
1742 "fields changes.";
1743
1744 fbb.Finish(configuration_builder.Finish());
1745
1746 // Clean it up and return it! By using MergeConfiguration here, we'll
1747 // actually get a deduplicated config for free too.
1748 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1749 configuration::MergeConfiguration(
1750 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1751
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001752 remapped_configuration_buffer_ =
1753 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001754 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001755
1756 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001757
1758 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001759}
1760
Austin Schuh6f3babe2020-01-26 20:34:50 -08001761const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1762 const Channel *channel) {
1763 std::string_view channel_name = channel->name()->string_view();
1764 std::string_view channel_type = channel->type()->string_view();
1765 const int channel_index =
1766 configuration::ChannelIndex(logged_configuration(), channel);
1767 // If the channel is remapped, find the correct channel name to use.
1768 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001769 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001770 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001771 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001772 }
1773
Austin Schuhee711052020-08-24 16:06:09 -07001774 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001775 const Channel *remapped_channel = configuration::GetChannel(
1776 event_loop->configuration(), channel_name, channel_type,
1777 event_loop->name(), event_loop->node());
1778
1779 CHECK(remapped_channel != nullptr)
1780 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1781 << channel_type << "\"} because it is not in the provided configuration.";
1782
1783 return remapped_channel;
1784}
1785
Austin Schuh287d43d2020-12-04 20:19:33 -08001786LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1787 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1788
1789void LogReader::State::AddPeer(State *peer) {
1790 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1791 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1792 }
1793}
Austin Schuh858c9f32020-08-31 16:56:12 -07001794
1795EventLoop *LogReader::State::SetNodeEventLoopFactory(
1796 NodeEventLoopFactory *node_event_loop_factory) {
1797 node_event_loop_factory_ = node_event_loop_factory;
1798 event_loop_unique_ptr_ =
1799 node_event_loop_factory_->MakeEventLoop("log_reader");
1800 return event_loop_unique_ptr_.get();
1801}
1802
1803void LogReader::State::SetChannelCount(size_t count) {
1804 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001805 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001806 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001807 channel_source_state_.resize(count);
1808 factory_channel_index_.resize(count);
1809 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001810}
1811
1812void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001813 size_t logged_channel_index, size_t factory_channel_index,
1814 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001815 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh0de30f32020-12-06 12:44:28 -08001816 aos::Sender<RemoteMessage> *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001817 channels_[logged_channel_index] = std::move(sender);
1818 filters_[logged_channel_index] = filter;
1819 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1820
1821 if (source_state) {
1822 channel_source_state_[logged_channel_index] = source_state;
1823
1824 if (remote_timestamp_sender != nullptr) {
1825 source_state->queue_index_map_[logged_channel_index] =
1826 std::make_unique<std::vector<State::SentTimestamp>>();
1827 }
1828 }
1829
1830 factory_channel_index_[logged_channel_index] = factory_channel_index;
1831}
1832
Austin Schuh287d43d2020-12-04 20:19:33 -08001833bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1834 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001835 uint32_t remote_queue_index = 0xffffffff;
1836
Austin Schuh287d43d2020-12-04 20:19:33 -08001837 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
1838 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
1839 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1840 ->queue_index_map_[timestamped_message.channel_index]
1841 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001842
1843 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08001844 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
1845 search.realtime_event_time = timestamped_message.realtime_remote_time;
1846 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001847
1848 // Find the sent time if available.
1849 auto element = std::lower_bound(
1850 queue_index_map->begin(), queue_index_map->end(), search,
1851 [](SentTimestamp a, SentTimestamp b) {
1852 if (b.monotonic_event_time < a.monotonic_event_time) {
1853 return false;
1854 }
1855 if (b.monotonic_event_time > a.monotonic_event_time) {
1856 return true;
1857 }
1858
1859 if (b.queue_index < a.queue_index) {
1860 return false;
1861 }
1862 if (b.queue_index > a.queue_index) {
1863 return true;
1864 }
1865
1866 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1867 return false;
1868 });
1869
1870 // TODO(austin): Be a bit more principled here, but we will want to do that
1871 // after the logger rewrite. We hit this when one node finishes, but the
1872 // other node isn't done yet. So there is no send time, but there is a
1873 // receive time.
1874 if (element != queue_index_map->end()) {
1875 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001876 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001877 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001878 timestamped_message.realtime_remote_time);
1879 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001880
1881 remote_queue_index = element->actual_queue_index;
1882 }
1883 }
1884
1885 // Send! Use the replayed queue index here instead of the logged queue index
1886 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001887 const bool sent = sender->Send(
1888 timestamped_message.data.message().data()->Data(),
1889 timestamped_message.data.message().data()->size(),
1890 timestamped_message.monotonic_remote_time,
1891 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001892 if (!sent) return false;
1893
Austin Schuh287d43d2020-12-04 20:19:33 -08001894 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001895 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08001896 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
1897 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
1898 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001899 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08001900 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1901 timestamp);
1902 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1903 nullptr) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001904 aos::Sender<RemoteMessage>::Builder builder =
Austin Schuh287d43d2020-12-04 20:19:33 -08001905 remote_timestamp_senders_[timestamped_message.channel_index]
1906 ->MakeBuilder();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001907
Austin Schuh315b96b2020-12-11 21:21:12 -08001908 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
1909 builder.fbb()->CreateString(event_loop_->boot_uuid().string_view());
1910
Austin Schuh0de30f32020-12-06 12:44:28 -08001911 RemoteMessage::Builder message_header_builder =
1912 builder.MakeBuilder<RemoteMessage>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001913
1914 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001915 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001916
1917 // Swap the remote and sent metrics. They are from the sender's
1918 // perspective, not the receiver's perspective.
1919 message_header_builder.add_monotonic_sent_time(
1920 sender->monotonic_sent_time().time_since_epoch().count());
1921 message_header_builder.add_realtime_sent_time(
1922 sender->realtime_sent_time().time_since_epoch().count());
1923 message_header_builder.add_queue_index(sender->sent_queue_index());
1924
1925 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001926 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001927 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001928 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929
1930 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001931 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001932
1933 builder.Send(message_header_builder.Finish());
1934 }
1935
1936 return true;
1937}
1938
Austin Schuh0de30f32020-12-06 12:44:28 -08001939aos::Sender<RemoteMessage> *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001940 const Node *delivered_node) {
1941 auto sender = remote_timestamp_senders_map_.find(delivered_node);
1942
1943 if (sender == remote_timestamp_senders_map_.end()) {
1944 sender = remote_timestamp_senders_map_
1945 .emplace(std::make_pair(
1946 delivered_node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001947 event_loop()->MakeSender<RemoteMessage>(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001948 absl::StrCat("/aos/remote_timestamps/",
1949 delivered_node->name()->string_view()))))
1950 .first;
1951 }
1952
1953 return &(sender->second);
Austin Schuh858c9f32020-08-31 16:56:12 -07001954}
1955
Austin Schuh287d43d2020-12-04 20:19:33 -08001956TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001957 CHECK_GT(sorted_messages_.size(), 0u);
1958
Austin Schuh287d43d2020-12-04 20:19:33 -08001959 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07001960 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001961 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07001962 << std::get<0>(result).monotonic_event_time;
1963 sorted_messages_.pop_front();
1964 SeedSortedMessages();
1965
Austin Schuh287d43d2020-12-04 20:19:33 -08001966 if (std::get<1>(result) != nullptr) {
1967 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07001968 event_loop_->node(), std::get<0>(result).monotonic_event_time);
1969 } else {
1970 *update_time = false;
1971 }
Austin Schuh287d43d2020-12-04 20:19:33 -08001972 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07001973}
1974
1975monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
1976 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001977 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07001978 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
1979 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
1980 }
1981
Austin Schuh287d43d2020-12-04 20:19:33 -08001982 TimestampedMessage *m =
1983 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
1984 if (m == nullptr) {
1985 return monotonic_clock::max_time;
1986 }
1987 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07001988}
1989
1990void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08001991 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07001992 const aos::monotonic_clock::time_point end_queue_time =
1993 (sorted_messages_.size() > 0
1994 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08001995 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08001996 chrono::duration_cast<chrono::seconds>(
1997 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07001998
1999 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002000 TimestampedMessage *m = timestamp_mapper_->Front();
2001 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002002 return;
2003 }
2004 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002005 // Stop placing sorted messages on the list once we have
2006 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2007 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002008 if (end_queue_time <
2009 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2010 return;
2011 }
2012 }
2013
Austin Schuh2f8fd752020-09-01 22:38:28 -07002014 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2015
Austin Schuh287d43d2020-12-04 20:19:33 -08002016 TimestampedMessage timestamped_message = std::move(*m);
2017 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002018
Austin Schuh2f8fd752020-09-01 22:38:28 -07002019 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002020 if (timestamped_message.monotonic_remote_time !=
2021 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002022 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002023 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002024
2025 CHECK(filter != nullptr);
2026
2027 // Call the correct method depending on if we are the forward or
2028 // reverse direction here.
2029 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002030 timestamped_message.monotonic_event_time,
2031 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002032 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002033 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002034 }
2035}
2036
2037void LogReader::State::Deregister() {
2038 for (size_t i = 0; i < channels_.size(); ++i) {
2039 channels_[i].reset();
2040 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002041 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002042 event_loop_unique_ptr_.reset();
2043 event_loop_ = nullptr;
2044 timer_handler_ = nullptr;
2045 node_event_loop_factory_ = nullptr;
2046}
2047
Austin Schuhe309d2a2019-11-29 13:25:21 -08002048} // namespace logger
2049} // namespace aos