blob: 2e0f5dbfae6ef44be78ab8f0f07f08f1a0226859 [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 Schuh8c399962020-12-25 21:51:45 -080025#include "openssl/sha.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070026#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027
Austin Schuh15649d62019-12-28 16:36:38 -080028DEFINE_bool(skip_missing_forwarding_entries, false,
29 "If true, drop any forwarding entries with missing data. If "
30 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080031
Austin Schuh0ca1fd32020-12-18 22:53:05 -080032DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080033
Austin Schuh2f8fd752020-09-01 22:38:28 -070034DEFINE_bool(skip_order_validation, false,
35 "If true, ignore any out of orderness in replay");
36
Austin Schuhf0688662020-12-19 15:37:45 -080037DEFINE_double(
38 time_estimation_buffer_seconds, 2.0,
39 "The time to buffer ahead in the log file to accurately reconstruct time.");
40
Austin Schuhe309d2a2019-11-29 13:25:21 -080041namespace aos {
42namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070043namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080044std::string Sha256(const absl::Span<const uint8_t> str) {
45 unsigned char hash[SHA256_DIGEST_LENGTH];
46 SHA256_CTX sha256;
47 SHA256_Init(&sha256);
48 SHA256_Update(&sha256, str.data(), str.size());
49 SHA256_Final(hash, &sha256);
50 std::stringstream ss;
51 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
52 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
53 }
54 return ss.str();
55}
56
Austin Schuh315b96b2020-12-11 21:21:12 -080057std::string LogFileVectorToString(std::vector<LogFile> log_files) {
58 std::stringstream ss;
59 for (const auto f : log_files) {
60 ss << f << "\n";
61 }
62 return ss.str();
63}
64
Austin Schuh0de30f32020-12-06 12:44:28 -080065// Copies the channel, removing the schema as we go. If new_name is provided,
66// it is used instead of the name inside the channel. If new_type is provided,
67// it is used instead of the type in the channel.
68flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
69 std::string_view new_name,
70 std::string_view new_type,
71 flatbuffers::FlatBufferBuilder *fbb) {
72 flatbuffers::Offset<flatbuffers::String> name_offset =
73 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
74 : new_name);
75 flatbuffers::Offset<flatbuffers::String> type_offset =
76 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
77 flatbuffers::Offset<flatbuffers::String> source_node_offset =
78 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
79 : 0;
80
81 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
82 destination_nodes_offset =
83 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
84
85 flatbuffers::Offset<
86 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
87 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
88
89 Channel::Builder channel_builder(*fbb);
90 channel_builder.add_name(name_offset);
91 channel_builder.add_type(type_offset);
92 if (c->has_frequency()) {
93 channel_builder.add_frequency(c->frequency());
94 }
95 if (c->has_max_size()) {
96 channel_builder.add_max_size(c->max_size());
97 }
98 if (c->has_num_senders()) {
99 channel_builder.add_num_senders(c->num_senders());
100 }
101 if (c->has_num_watchers()) {
102 channel_builder.add_num_watchers(c->num_watchers());
103 }
104 if (!source_node_offset.IsNull()) {
105 channel_builder.add_source_node(source_node_offset);
106 }
107 if (!destination_nodes_offset.IsNull()) {
108 channel_builder.add_destination_nodes(destination_nodes_offset);
109 }
110 if (c->has_logger()) {
111 channel_builder.add_logger(c->logger());
112 }
113 if (!logger_nodes_offset.IsNull()) {
114 channel_builder.add_logger_nodes(logger_nodes_offset);
115 }
116 if (c->has_read_method()) {
117 channel_builder.add_read_method(c->read_method());
118 }
119 if (c->has_num_readers()) {
120 channel_builder.add_num_readers(c->num_readers());
121 }
122 return channel_builder.Finish();
123}
124
Austin Schuhe309d2a2019-11-29 13:25:21 -0800125namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800126using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700127} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800128
Brian Silverman1f345222020-09-24 21:14:48 -0700129Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
130 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800131 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700132 configuration_(configuration),
133 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700134 timer_handler_(event_loop_->AddTimer(
135 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700136 server_statistics_fetcher_(
137 configuration::MultiNode(event_loop_->configuration())
138 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
139 "/aos")
140 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700141 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700142
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700143 // Find all the nodes which are logging timestamps on our node. This may
144 // over-estimate if should_log is specified.
145 std::vector<const Node *> timestamp_logger_nodes =
146 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147
148 std::map<const Channel *, const Node *> timestamp_logger_channels;
149
150 // Now that we have all the nodes accumulated, make remote timestamp loggers
151 // for them.
152 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700153 // Note: since we are doing a find using the event loop channel, we need to
154 // make sure this channel pointer is part of the event loop configuration,
155 // not configuration_. This only matters when configuration_ !=
156 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700158 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800160 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700161 event_loop_->node());
162
163 CHECK(channel != nullptr)
164 << ": Remote timestamps are logged on "
165 << event_loop_->node()->name()->string_view()
166 << " but can't find channel /aos/remote_timestamps/"
167 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700168 if (!should_log(channel)) {
169 continue;
170 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700171 timestamp_logger_channels.insert(std::make_pair(channel, node));
172 }
173
Brian Silvermand90905f2020-09-23 14:42:56 -0700174 const size_t our_node_index =
175 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700176
Brian Silverman1f345222020-09-24 21:14:48 -0700177 for (size_t channel_index = 0;
178 channel_index < configuration_->channels()->size(); ++channel_index) {
179 const Channel *const config_channel =
180 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700181 // The MakeRawFetcher method needs a channel which is in the event loop
182 // configuration() object, not the configuration_ object. Go look that up
183 // from the config.
184 const Channel *channel = aos::configuration::GetChannel(
185 event_loop_->configuration(), config_channel->name()->string_view(),
186 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700187 CHECK(channel != nullptr)
188 << ": Failed to look up channel "
189 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700190 if (!should_log(channel)) {
191 continue;
192 }
Austin Schuh0c297012020-09-16 18:41:59 -0700193
Austin Schuhe309d2a2019-11-29 13:25:21 -0800194 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700195 fs.channel_index = channel_index;
196 fs.channel = channel;
197
Austin Schuh6f3babe2020-01-26 20:34:50 -0800198 const bool is_local =
199 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
200
Austin Schuh15649d62019-12-28 16:36:38 -0800201 const bool is_readable =
202 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700203 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
204 channel, event_loop_->node());
205 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800206
Brian Silverman1f345222020-09-24 21:14:48 -0700207 bool log_delivery_times = false;
208 if (event_loop_->node() != nullptr) {
209 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
210 channel, event_loop_->node(), event_loop_->node());
211 }
Austin Schuh15649d62019-12-28 16:36:38 -0800212
Austin Schuh0de30f32020-12-06 12:44:28 -0800213 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700214 // contents to a file directly.
215 const bool log_contents = timestamp_logger_channels.find(channel) !=
216 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700217
218 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800219 fs.fetcher = event_loop->MakeRawFetcher(channel);
220 VLOG(1) << "Logging channel "
221 << configuration::CleanedChannelToString(channel);
222
223 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700225 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800226 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800227 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800228 if (log_message) {
229 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700230 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800231 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800232 const Node *source_node = configuration::GetNode(
233 configuration_, channel->source_node()->string_view());
234 fs.data_node_index =
235 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800237 } else {
238 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800239 }
240 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700241 if (log_contents) {
242 VLOG(1) << "Timestamp logger channel "
243 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700244 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
245 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800246 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700247 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700248 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800249 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800250 }
Brian Silverman1f345222020-09-24 21:14:48 -0700251 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700252
253 // When we are logging remote timestamps, we need to be able to translate from
254 // the channel index that the event loop uses to the channel index in the
255 // config in the log file.
256 event_loop_to_logged_channel_index_.resize(
257 event_loop->configuration()->channels()->size(), -1);
258 for (size_t event_loop_channel_index = 0;
259 event_loop_channel_index <
260 event_loop->configuration()->channels()->size();
261 ++event_loop_channel_index) {
262 const Channel *event_loop_channel =
263 event_loop->configuration()->channels()->Get(event_loop_channel_index);
264
265 const Channel *logged_channel = aos::configuration::GetChannel(
266 configuration_, event_loop_channel->name()->string_view(),
267 event_loop_channel->type()->string_view(), "",
268 configuration::GetNode(configuration_, event_loop_->node()));
269
270 if (logged_channel != nullptr) {
271 event_loop_to_logged_channel_index_[event_loop_channel_index] =
272 configuration::ChannelIndex(configuration_, logged_channel);
273 }
274 }
Brian Silverman1f345222020-09-24 21:14:48 -0700275}
276
277Logger::~Logger() {
278 if (log_namer_) {
279 // If we are replaying a log file, or in simulation, we want to force the
280 // last bit of data to be logged. The easiest way to deal with this is to
281 // poll everything as we go to destroy the class, ie, shut down the logger,
282 // and write it to disk.
283 StopLogging(event_loop_->monotonic_now());
284 }
285}
286
Brian Silvermanae7c0332020-09-30 16:58:23 -0700287void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
288 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700289 CHECK(!log_namer_) << ": Already logging";
290 log_namer_ = std::move(log_namer);
Austin Schuh8c399962020-12-25 21:51:45 -0800291
292 std::string config_sha256;
293 if (separate_config_) {
294 flatbuffers::FlatBufferBuilder fbb;
295 flatbuffers::Offset<aos::Configuration> configuration_offset =
296 CopyFlatBuffer(configuration_, &fbb);
297 LogFileHeader::Builder log_file_header_builder(fbb);
298 log_file_header_builder.add_configuration(configuration_offset);
299 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
300 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> config_header(
301 fbb.Release());
302 config_sha256 = Sha256(config_header.span());
303 LOG(INFO) << "Config sha256 of " << config_sha256;
304 log_namer_->WriteConfiguration(&config_header, config_sha256);
305 }
306
Brian Silvermanae7c0332020-09-30 16:58:23 -0700307 log_event_uuid_ = UUID::Random();
308 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700309 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
310
311 // We want to do as much work as possible before the initial Fetch. Time
312 // between that and actually starting to log opens up the possibility of
313 // falling off the end of the queue during that time.
314
315 for (FetcherStruct &f : fetchers_) {
316 if (f.wants_writer) {
317 f.writer = log_namer_->MakeWriter(f.channel);
318 }
319 if (f.wants_timestamp_writer) {
320 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
321 }
322 if (f.wants_contents_writer) {
323 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
324 f.channel, CHECK_NOTNULL(f.timestamp_node));
325 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800326 }
327
Brian Silverman1f345222020-09-24 21:14:48 -0700328 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700329 node_state_.resize(configuration::MultiNode(configuration_)
330 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700331 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800332
Austin Schuh2f8fd752020-09-01 22:38:28 -0700333 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700334 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800335
Austin Schuh8c399962020-12-25 21:51:45 -0800336 node_state_[node_index].log_file_header =
337 MakeHeader(node, config_sha256);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700338 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800339
Austin Schuh2f8fd752020-09-01 22:38:28 -0700340 // Grab data from each channel right before we declare the log file started
341 // so we can capture the latest message on each channel. This lets us have
342 // non periodic messages with configuration that now get logged.
343 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700344 const auto start = event_loop_->monotonic_now();
345 const bool got_new = f.fetcher->Fetch();
346 const auto end = event_loop_->monotonic_now();
347 RecordFetchResult(start, end, got_new, &f);
348
349 // If there is a message, we want to write it.
350 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700351 }
352
353 // Clear out any old timestamps in case we are re-starting logging.
354 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800355 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
356 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700357 }
358
359 WriteHeader();
360
361 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
362 << " start_time " << last_synchronized_time_;
363
Austin Schuh315b96b2020-12-11 21:21:12 -0800364 // Force logging up until the start of the log file now, so the messages at
365 // the start are always ordered before the rest of the messages.
366 // Note: this ship may have already sailed, but we don't have to make it
367 // worse.
368 // TODO(austin): Test...
369 LogUntil(last_synchronized_time_);
370
Austin Schuh2f8fd752020-09-01 22:38:28 -0700371 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
372 polling_period_);
373}
374
Brian Silverman1f345222020-09-24 21:14:48 -0700375std::unique_ptr<LogNamer> Logger::StopLogging(
376 aos::monotonic_clock::time_point end_time) {
377 CHECK(log_namer_) << ": Not logging right now";
378
379 if (end_time != aos::monotonic_clock::min_time) {
380 LogUntil(end_time);
381 }
382 timer_handler_->Disable();
383
384 for (FetcherStruct &f : fetchers_) {
385 f.writer = nullptr;
386 f.timestamp_writer = nullptr;
387 f.contents_writer = nullptr;
388 }
389 node_state_.clear();
390
Brian Silvermanae7c0332020-09-30 16:58:23 -0700391 log_event_uuid_ = UUID::Zero();
392 log_start_uuid_ = std::string();
393
Brian Silverman1f345222020-09-24 21:14:48 -0700394 return std::move(log_namer_);
395}
396
Austin Schuhfa895892020-01-07 20:07:41 -0800397void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700398 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700399 server_statistics_fetcher_.Fetch();
400 }
401
402 aos::monotonic_clock::time_point monotonic_start_time =
403 event_loop_->monotonic_now();
404 aos::realtime_clock::time_point realtime_start_time =
405 event_loop_->realtime_now();
406
407 // We need to pick a point in time to declare the log file "started". This
408 // starts here. It needs to be after everything is fetched so that the
409 // fetchers are all pointed at the most recent message before the start
410 // time.
411 last_synchronized_time_ = monotonic_start_time;
412
Austin Schuh6f3babe2020-01-26 20:34:50 -0800413 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700414 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700415 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
416 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800417 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418 }
419}
Austin Schuh8bd96322020-02-13 21:18:22 -0800420
Austin Schuh315b96b2020-12-11 21:21:12 -0800421void Logger::MaybeWriteHeader(int node_index) {
422 if (configuration::MultiNode(configuration_)) {
423 return MaybeWriteHeader(node_index,
424 configuration_->nodes()->Get(node_index));
425 } else {
426 return MaybeWriteHeader(node_index, nullptr);
427 }
428}
429
430void Logger::MaybeWriteHeader(int node_index, const Node *node) {
431 // This function is responsible for writing the header when the header both
432 // has valid data, and when it needs to be written.
433 if (node_state_[node_index].header_written &&
434 node_state_[node_index].header_valid) {
435 // The header has been written and is valid, nothing to do.
436 return;
437 }
438 if (!node_state_[node_index].has_source_node_boot_uuid) {
439 // Can't write a header if we don't have the boot UUID.
440 return;
441 }
442
443 // WriteHeader writes the first header in a log file. We want to do this only
444 // once.
445 //
446 // Rotate rewrites the same header with a new part ID, but keeps the same part
447 // UUID. We don't want that when things reboot, because that implies that
448 // parts go together across a reboot.
449 //
450 // Reboot resets the parts UUID. So, once we've written a header the first
451 // time, we want to use Reboot to rotate the log and reset the parts UUID.
452 //
453 // header_valid is cleared whenever the remote reboots.
454 if (node_state_[node_index].header_written) {
455 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
456 } else {
457 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
458
459 node_state_[node_index].header_written = true;
460 }
461 node_state_[node_index].header_valid = true;
462}
463
Austin Schuh2f8fd752020-09-01 22:38:28 -0700464void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700465 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700466 server_statistics_fetcher_.Fetch();
467 } else {
468 return;
469 }
470
471 if (server_statistics_fetcher_.get() == nullptr) {
472 return;
473 }
474
475 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700476 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700477 if (MaybeUpdateTimestamp(
478 node, node_index,
479 server_statistics_fetcher_.context().monotonic_event_time,
480 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800481 CHECK(node_state_[node_index].header_written);
482 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700483 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800484 } else {
485 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700486 }
487 }
488}
489
Austin Schuh315b96b2020-12-11 21:21:12 -0800490void Logger::SetStartTime(
491 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
492 aos::realtime_clock::time_point realtime_start_time,
493 aos::monotonic_clock::time_point logger_monotonic_start_time,
494 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700495 node_state_[node_index].monotonic_start_time = monotonic_start_time;
496 node_state_[node_index].realtime_start_time = realtime_start_time;
497 node_state_[node_index]
498 .log_file_header.mutable_message()
499 ->mutate_monotonic_start_time(
500 std::chrono::duration_cast<std::chrono::nanoseconds>(
501 monotonic_start_time.time_since_epoch())
502 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800503
504 // Add logger start times if they are available in the log file header.
505 if (node_state_[node_index]
506 .log_file_header.mutable_message()
507 ->has_logger_monotonic_start_time()) {
508 node_state_[node_index]
509 .log_file_header.mutable_message()
510 ->mutate_logger_monotonic_start_time(
511 std::chrono::duration_cast<std::chrono::nanoseconds>(
512 logger_monotonic_start_time.time_since_epoch())
513 .count());
514 }
515
516 if (node_state_[node_index]
517 .log_file_header.mutable_message()
518 ->has_logger_realtime_start_time()) {
519 node_state_[node_index]
520 .log_file_header.mutable_message()
521 ->mutate_logger_realtime_start_time(
522 std::chrono::duration_cast<std::chrono::nanoseconds>(
523 logger_realtime_start_time.time_since_epoch())
524 .count());
525 }
526
Austin Schuh2f8fd752020-09-01 22:38:28 -0700527 if (node_state_[node_index]
528 .log_file_header.mutable_message()
529 ->has_realtime_start_time()) {
530 node_state_[node_index]
531 .log_file_header.mutable_message()
532 ->mutate_realtime_start_time(
533 std::chrono::duration_cast<std::chrono::nanoseconds>(
534 realtime_start_time.time_since_epoch())
535 .count());
536 }
537}
538
539bool Logger::MaybeUpdateTimestamp(
540 const Node *node, int node_index,
541 aos::monotonic_clock::time_point monotonic_start_time,
542 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700543 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700544 if (node_state_[node_index].monotonic_start_time !=
545 monotonic_clock::min_time) {
546 return false;
547 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800548 if (event_loop_->node() == node ||
549 !configuration::MultiNode(configuration_)) {
550 // There are no offsets to compute for ourself, so always succeed.
551 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
552 monotonic_start_time, realtime_start_time);
553 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700554 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800555 } else if (server_statistics_fetcher_.get() != nullptr) {
556 // We must be a remote node now. Look for the connection and see if it is
557 // connected.
558
559 for (const message_bridge::ServerConnection *connection :
560 *server_statistics_fetcher_->connections()) {
561 if (connection->node()->name()->string_view() !=
562 node->name()->string_view()) {
563 continue;
564 }
565
566 if (connection->state() != message_bridge::State::CONNECTED) {
567 VLOG(1) << node->name()->string_view()
568 << " is not connected, can't start it yet.";
569 break;
570 }
571
572 // Update the boot UUID as soon as we know we are connected.
573 if (!connection->has_boot_uuid()) {
574 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
575 break;
576 }
577
578 if (!node_state_[node_index].has_source_node_boot_uuid ||
579 node_state_[node_index].source_node_boot_uuid !=
580 connection->boot_uuid()->string_view()) {
581 node_state_[node_index].SetBootUUID(
582 connection->boot_uuid()->string_view());
583 }
584
585 if (!connection->has_monotonic_offset()) {
586 VLOG(1) << "Missing monotonic offset for setting start time for node "
587 << aos::FlatbufferToJson(node);
588 break;
589 }
590
591 // Found it and it is connected. Compensate and go.
592 SetStartTime(node_index,
593 monotonic_start_time +
594 std::chrono::nanoseconds(connection->monotonic_offset()),
595 realtime_start_time, monotonic_start_time,
596 realtime_start_time);
597 return true;
598 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700599 }
600 return false;
601}
602
603aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
Austin Schuh8c399962020-12-25 21:51:45 -0800604 const Node *node, std::string_view config_sha256) {
Austin Schuhfa895892020-01-07 20:07:41 -0800605 // Now write the header with this timestamp in it.
606 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800607 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800608
Austin Schuh8c399962020-12-25 21:51:45 -0800609 flatbuffers::Offset<aos::Configuration> configuration_offset;
610 if (!separate_config_) {
611 configuration_offset = CopyFlatBuffer(configuration_, &fbb);
612 } else {
613 CHECK(!config_sha256.empty());
614 }
Austin Schuhfa895892020-01-07 20:07:41 -0800615
Brian Silvermanae7c0332020-09-30 16:58:23 -0700616 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700617 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800618
Brian Silvermanae7c0332020-09-30 16:58:23 -0700619 CHECK(log_event_uuid_ != UUID::Zero());
620 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
621 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700622
Brian Silvermanae7c0332020-09-30 16:58:23 -0700623 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
624 fbb.CreateString(logger_instance_uuid_.string_view());
625
626 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
627 if (!log_start_uuid_.empty()) {
628 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
629 }
630
Austin Schuh8c399962020-12-25 21:51:45 -0800631 flatbuffers::Offset<flatbuffers::String> config_sha256_offset;
632 if (!config_sha256.empty()) {
633 config_sha256_offset = fbb.CreateString(config_sha256);
634 }
635
Austin Schuh315b96b2020-12-11 21:21:12 -0800636 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
637 fbb.CreateString(event_loop_->boot_uuid().string_view());
638
639 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
640 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700641
642 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700643 fbb.CreateString("00000000-0000-4000-8000-000000000000");
644
Austin Schuhfa895892020-01-07 20:07:41 -0800645 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700646 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700647
Austin Schuh0c297012020-09-16 18:41:59 -0700648 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800649 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
650 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800651 }
652
653 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
654
Austin Schuh64fab802020-09-09 22:47:47 -0700655 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800656
657 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800658 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800659 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700660 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800661 }
662
Austin Schuh8c399962020-12-25 21:51:45 -0800663 if (!configuration_offset.IsNull()) {
664 log_file_header_builder.add_configuration(configuration_offset);
665 }
Austin Schuhfa895892020-01-07 20:07:41 -0800666 // The worst case theoretical out of order is the polling period times 2.
667 // One message could get logged right after the boundary, but be for right
668 // before the next boundary. And the reverse could happen for another
669 // message. Report back 3x to be extra safe, and because the cost isn't
670 // huge on the read side.
671 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700672 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800673
674 log_file_header_builder.add_monotonic_start_time(
675 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700676 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800677 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700678 if (node == event_loop_->node()) {
679 log_file_header_builder.add_realtime_start_time(
680 std::chrono::duration_cast<std::chrono::nanoseconds>(
681 realtime_clock::min_time.time_since_epoch())
682 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800683 } else {
684 log_file_header_builder.add_logger_monotonic_start_time(
685 std::chrono::duration_cast<std::chrono::nanoseconds>(
686 monotonic_clock::min_time.time_since_epoch())
687 .count());
688 log_file_header_builder.add_logger_realtime_start_time(
689 std::chrono::duration_cast<std::chrono::nanoseconds>(
690 realtime_clock::min_time.time_since_epoch())
691 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800692 }
693
Brian Silvermanae7c0332020-09-30 16:58:23 -0700694 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
695 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
696 if (!log_start_uuid_offset.IsNull()) {
697 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
698 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800699 log_file_header_builder.add_logger_node_boot_uuid(
700 logger_node_boot_uuid_offset);
701 log_file_header_builder.add_source_node_boot_uuid(
702 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700703
704 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
705 log_file_header_builder.add_parts_index(0);
706
Austin Schuh8c399962020-12-25 21:51:45 -0800707 log_file_header_builder.add_configuration_sha256(0);
708
709 if (!config_sha256_offset.IsNull()) {
710 log_file_header_builder.add_configuration_sha256(config_sha256_offset);
711 }
712
Austin Schuh2f8fd752020-09-01 22:38:28 -0700713 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800714 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
715 fbb.Release());
716
717 CHECK(result.Verify()) << ": Built a corrupted header.";
718
719 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720}
721
Brian Silvermancb805822020-10-06 17:43:35 -0700722void Logger::ResetStatisics() {
723 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
724 max_message_fetch_time_channel_ = -1;
725 max_message_fetch_time_size_ = -1;
726 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
727 total_message_fetch_count_ = 0;
728 total_message_fetch_bytes_ = 0;
729 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
730 total_nop_fetch_count_ = 0;
731 max_copy_time_ = std::chrono::nanoseconds::zero();
732 max_copy_time_channel_ = -1;
733 max_copy_time_size_ = -1;
734 total_copy_time_ = std::chrono::nanoseconds::zero();
735 total_copy_count_ = 0;
736 total_copy_bytes_ = 0;
737}
738
Austin Schuh2f8fd752020-09-01 22:38:28 -0700739void Logger::Rotate() {
740 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700741 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700742 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700743 }
744}
745
746void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800747 // Grab the latest ServerStatistics message. This will always have the
748 // oppertunity to be >= to the current time, so it will always represent any
749 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700750 WriteMissingTimestamps();
751
752 // Write each channel to disk, one at a time.
753 for (FetcherStruct &f : fetchers_) {
754 while (true) {
755 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700756 const auto start = event_loop_->monotonic_now();
757 const bool got_new = f.fetcher->FetchNext();
758 const auto end = event_loop_->monotonic_now();
759 RecordFetchResult(start, end, got_new, &f);
760 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700761 VLOG(2) << "No new data on "
762 << configuration::CleanedChannelToString(
763 f.fetcher->channel());
764 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700765 }
Brian Silvermancb805822020-10-06 17:43:35 -0700766 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700767 }
768
Austin Schuh2f8fd752020-09-01 22:38:28 -0700769 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700770 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700771 break;
772 }
Brian Silvermancb805822020-10-06 17:43:35 -0700773 if (f.writer != nullptr) {
774 // Write!
775 const auto start = event_loop_->monotonic_now();
776 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
777 max_header_size_);
778 fbb.ForceDefaults(true);
779
780 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
781 f.channel_index, f.log_type));
782 const auto end = event_loop_->monotonic_now();
783 RecordCreateMessageTime(start, end, &f);
784
785 VLOG(2) << "Writing data as node "
786 << FlatbufferToJson(event_loop_->node()) << " for channel "
787 << configuration::CleanedChannelToString(f.fetcher->channel())
788 << " to " << f.writer->filename() << " data "
789 << FlatbufferToJson(
790 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
791 fbb.GetBufferPointer()));
792
793 max_header_size_ = std::max(max_header_size_,
794 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800795 CHECK(node_state_[f.data_node_index].header_valid)
796 << ": Can't write data before the header on channel "
797 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700798 f.writer->QueueSizedFlatbuffer(&fbb);
799 }
800
801 if (f.timestamp_writer != nullptr) {
802 // And now handle timestamps.
803 const auto start = event_loop_->monotonic_now();
804 flatbuffers::FlatBufferBuilder fbb;
805 fbb.ForceDefaults(true);
806
807 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
808 f.channel_index,
809 LogType::kLogDeliveryTimeOnly));
810 const auto end = event_loop_->monotonic_now();
811 RecordCreateMessageTime(start, end, &f);
812
813 VLOG(2) << "Writing timestamps as node "
814 << FlatbufferToJson(event_loop_->node()) << " for channel "
815 << configuration::CleanedChannelToString(f.fetcher->channel())
816 << " to " << f.timestamp_writer->filename() << " timestamp "
817 << FlatbufferToJson(
818 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
819 fbb.GetBufferPointer()));
820
Austin Schuh315b96b2020-12-11 21:21:12 -0800821 CHECK(node_state_[f.timestamp_node_index].header_valid)
822 << ": Can't write data before the header on channel "
823 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700824 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
825 }
826
827 if (f.contents_writer != nullptr) {
828 const auto start = event_loop_->monotonic_now();
829 // And now handle the special message contents channel. Copy the
830 // message into a FlatBufferBuilder and save it to disk.
831 // TODO(austin): We can be more efficient here when we start to
832 // care...
833 flatbuffers::FlatBufferBuilder fbb;
834 fbb.ForceDefaults(true);
835
Austin Schuh0de30f32020-12-06 12:44:28 -0800836 const RemoteMessage *msg =
837 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700838
Austin Schuh315b96b2020-12-11 21:21:12 -0800839 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
840 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
841 node_state_[f.contents_node_index].source_node_boot_uuid !=
842 msg->boot_uuid()->string_view()) {
843 node_state_[f.contents_node_index].SetBootUUID(
844 msg->boot_uuid()->string_view());
845
846 MaybeWriteHeader(f.contents_node_index);
847 }
848
Brian Silvermancb805822020-10-06 17:43:35 -0700849 logger::MessageHeader::Builder message_header_builder(fbb);
850
851 // TODO(austin): This needs to check the channel_index and confirm
852 // that it should be logged before squirreling away the timestamp to
853 // disk. We don't want to log irrelevant timestamps.
854
855 // Note: this must match the same order as MessageBridgeServer and
856 // PackMessage. We want identical headers to have identical
857 // on-the-wire formats to make comparing them easier.
858
859 // Translate from the channel index that the event loop uses to the
860 // channel index in the log file.
861 message_header_builder.add_channel_index(
862 event_loop_to_logged_channel_index_[msg->channel_index()]);
863
864 message_header_builder.add_queue_index(msg->queue_index());
865 message_header_builder.add_monotonic_sent_time(
866 msg->monotonic_sent_time());
867 message_header_builder.add_realtime_sent_time(
868 msg->realtime_sent_time());
869
870 message_header_builder.add_monotonic_remote_time(
871 msg->monotonic_remote_time());
872 message_header_builder.add_realtime_remote_time(
873 msg->realtime_remote_time());
874 message_header_builder.add_remote_queue_index(
875 msg->remote_queue_index());
876
Austin Schuh969cd602021-01-03 00:09:45 -0800877 message_header_builder.add_monotonic_timestamp_time(
878 f.fetcher->context()
879 .monotonic_event_time.time_since_epoch()
880 .count());
881
Brian Silvermancb805822020-10-06 17:43:35 -0700882 fbb.FinishSizePrefixed(message_header_builder.Finish());
883 const auto end = event_loop_->monotonic_now();
884 RecordCreateMessageTime(start, end, &f);
885
Austin Schuh315b96b2020-12-11 21:21:12 -0800886 CHECK(node_state_[f.contents_node_index].header_valid)
887 << ": Can't write data before the header on channel "
888 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700889 f.contents_writer->QueueSizedFlatbuffer(&fbb);
890 }
891
892 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700893 }
894 }
895 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800896}
897
Brian Silverman1f345222020-09-24 21:14:48 -0700898void Logger::DoLogData(const monotonic_clock::time_point end_time) {
899 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800900 // max_out_of_order_duration. To do this, we need sync points. Every write
901 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800902
903 do {
904 // Move the sync point up by at most polling_period. This forces one sync
905 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700906 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
907
908 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800909
Austin Schuhe309d2a2019-11-29 13:25:21 -0800910 // If we missed cycles, we could be pretty far behind. Spin until we are
911 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700912 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800913}
914
Brian Silvermancb805822020-10-06 17:43:35 -0700915void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
916 aos::monotonic_clock::time_point end,
917 bool got_new, FetcherStruct *fetcher) {
918 const auto duration = end - start;
919 if (!got_new) {
920 ++total_nop_fetch_count_;
921 total_nop_fetch_time_ += duration;
922 return;
923 }
924 ++total_message_fetch_count_;
925 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
926 total_message_fetch_time_ += duration;
927 if (duration > max_message_fetch_time_) {
928 max_message_fetch_time_ = duration;
929 max_message_fetch_time_channel_ = fetcher->channel_index;
930 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
931 }
932}
933
934void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
935 aos::monotonic_clock::time_point end,
936 FetcherStruct *fetcher) {
937 const auto duration = end - start;
938 total_copy_time_ += duration;
939 ++total_copy_count_;
940 total_copy_bytes_ += fetcher->fetcher->context().size;
941 if (duration > max_copy_time_) {
942 max_copy_time_ = duration;
943 max_copy_time_channel_ = fetcher->channel_index;
944 max_copy_time_size_ = fetcher->fetcher->context().size;
945 }
946}
947
Austin Schuh11d43732020-09-21 17:28:30 -0700948std::vector<std::vector<std::string>> ToLogReaderVector(
949 const std::vector<LogFile> &log_files) {
950 std::vector<std::vector<std::string>> result;
951 for (const LogFile &log_file : log_files) {
952 for (const LogParts &log_parts : log_file.parts) {
953 std::vector<std::string> parts;
954 for (const std::string &part : log_parts.parts) {
955 parts.emplace_back(part);
956 }
957 result.emplace_back(std::move(parts));
958 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700959 }
960 return result;
961}
962
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800963LogReader::LogReader(std::string_view filename,
964 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800965 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800966
Austin Schuh287d43d2020-12-04 20:19:33 -0800967LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800968 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800969 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800970 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800971 CHECK_GT(log_files_.size(), 0u);
972 {
973 // Validate that we have the same config everwhere. This will be true if
974 // all the parts were sorted together and the configs match.
975 const Configuration *config = nullptr;
976 for (const LogFile &log_file : log_files) {
977 if (config == nullptr) {
978 config = log_file.config.get();
979 } else {
980 CHECK_EQ(config, log_file.config.get());
981 }
982 }
983 }
Austin Schuh6331ef92020-01-07 18:28:09 -0800984 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800985
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700986 // Remap all existing remote timestamp channels. They will be recreated, and
987 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700988 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700989 std::vector<const Node *> timestamp_logger_nodes =
990 configuration::TimestampNodes(logged_configuration(), node);
991 for (const Node *remote_node : timestamp_logger_nodes) {
992 const std::string channel = absl::StrCat(
993 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800994 // See if the log file is an old log with MessageHeader channels in it, or
995 // a newer log with RemoteMessage. If we find an older log, rename the
996 // type too along with the name.
997 if (HasChannel<MessageHeader>(channel, node)) {
998 CHECK(!HasChannel<RemoteMessage>(channel, node))
999 << ": Can't have both a MessageHeader and RemoteMessage remote "
1000 "timestamp channel.";
1001 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
1002 "aos.message_bridge.RemoteMessage");
1003 } else {
1004 CHECK(HasChannel<RemoteMessage>(channel, node))
1005 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
1006 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
1007 << node->name()->string_view();
1008 RemapLoggedChannel<RemoteMessage>(channel, node);
1009 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001010 }
1011 }
1012
Austin Schuh6aa77be2020-02-22 21:06:40 -08001013 if (replay_configuration) {
1014 CHECK_EQ(configuration::MultiNode(configuration()),
1015 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 << ": Log file and replay config need to both be multi or single "
1017 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -08001018 }
1019
Austin Schuh6f3babe2020-01-26 20:34:50 -08001020 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001021 states_.emplace_back(std::make_unique<State>(
1022 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -08001023 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001024 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -07001025 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -08001026 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -07001027 << ": Log file and replay config need to have matching nodes "
1028 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001029 for (const Node *node : *logged_configuration()->nodes()) {
1030 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001031 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
1032 << " in logged config that is not present in the replay "
1033 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001034 }
1035 }
Austin Schuh6aa77be2020-02-22 21:06:40 -08001036 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001037 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001038 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001039}
1040
Austin Schuh6aa77be2020-02-22 21:06:40 -08001041LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -07001042 if (event_loop_factory_unique_ptr_) {
1043 Deregister();
1044 } else if (event_loop_factory_ != nullptr) {
1045 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
1046 "is destroyed";
1047 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001048 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1049 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001050 if (remapped_configuration_buffer_) {
1051 remapped_configuration_buffer_->Wipe();
1052 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001053}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001054
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001055const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001056 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001057}
1058
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001059const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001060 return remapped_configuration_;
1061}
1062
Austin Schuh6f3babe2020-01-26 20:34:50 -08001063std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 // Because the Node pointer will only be valid if it actually points to
1065 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001066 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001067 //
1068 // Also, note, that when ever a map is changed, the nodes in here are
1069 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001070 CHECK(remapped_configuration_ != nullptr)
1071 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001072 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001073}
Austin Schuh15649d62019-12-28 16:36:38 -08001074
Austin Schuh11d43732020-09-21 17:28:30 -07001075monotonic_clock::time_point LogReader::monotonic_start_time(
1076 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001077 State *state =
1078 states_[configuration::GetNodeIndex(configuration(), node)].get();
1079 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1080
Austin Schuh858c9f32020-08-31 16:56:12 -07001081 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001082}
1083
Austin Schuh11d43732020-09-21 17:28:30 -07001084realtime_clock::time_point LogReader::realtime_start_time(
1085 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001086 State *state =
1087 states_[configuration::GetNodeIndex(configuration(), node)].get();
1088 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1089
Austin Schuh858c9f32020-08-31 16:56:12 -07001090 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001091}
1092
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001093void LogReader::Register() {
1094 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001095 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001096 Register(event_loop_factory_unique_ptr_.get());
1097}
1098
Austin Schuh92547522019-12-28 14:33:43 -08001099void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001100 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001101 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001102 filters_ =
1103 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuh87dd3832021-01-01 23:07:31 -08001104 event_loop_factory_, logged_configuration(),
1105 FLAGS_skip_order_validation);
Austin Schuh92547522019-12-28 14:33:43 -08001106
Brian Silvermand90905f2020-09-23 14:42:56 -07001107 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001108 const size_t node_index =
1109 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001110 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1111 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001112
1113 // Confirm that all the parts are from the same boot if there are enough
1114 // parts to not be from the same boot.
1115 if (filtered_parts.size() > 1u) {
1116 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1117 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1118 filtered_parts[0].source_boot_uuid)
1119 << ": Found parts from different boots "
1120 << LogFileVectorToString(log_files_);
1121 }
1122 }
1123
Austin Schuh287d43d2020-12-04 20:19:33 -08001124 states_[node_index] = std::make_unique<State>(
1125 filtered_parts.size() == 0u
1126 ? nullptr
1127 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001128 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001129 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001130 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001131
1132 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001133 }
Austin Schuh87dd3832021-01-01 23:07:31 -08001134 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001135
Austin Schuh287d43d2020-12-04 20:19:33 -08001136 for (const Node *node : configuration::GetNodes(configuration())) {
1137 const size_t node_index =
1138 configuration::GetNodeIndex(configuration(), node);
1139 State *state = states_[node_index].get();
1140 for (const Node *other_node : configuration::GetNodes(configuration())) {
1141 const size_t other_node_index =
1142 configuration::GetNodeIndex(configuration(), other_node);
1143 State *other_state = states_[other_node_index].get();
1144 if (other_state != state) {
1145 state->AddPeer(other_state);
1146 }
1147 }
1148 }
1149
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001150 // Register after making all the State objects so we can build references
1151 // between them.
1152 for (const Node *node : configuration::GetNodes(configuration())) {
1153 const size_t node_index =
1154 configuration::GetNodeIndex(configuration(), node);
1155 State *state = states_[node_index].get();
1156
1157 Register(state->event_loop());
1158 }
1159
James Kuszmaul46d82582020-05-09 19:50:09 -07001160 if (live_nodes_ == 0) {
1161 LOG(FATAL)
1162 << "Don't have logs from any of the nodes in the replay config--are "
1163 "you sure that the replay config matches the original config?";
1164 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001165
Austin Schuh87dd3832021-01-01 23:07:31 -08001166 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001167
Austin Schuh858c9f32020-08-31 16:56:12 -07001168 for (std::unique_ptr<State> &state : states_) {
1169 state->SeedSortedMessages();
1170 }
1171
Austin Schuh2f8fd752020-09-01 22:38:28 -07001172 // We want to start the log file at the last start time of the log files
1173 // from all the nodes. Compute how long each node's simulation needs to run
1174 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001175 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001176
Austin Schuh2f8fd752020-09-01 22:38:28 -07001177 // TODO(austin): We want an "OnStart" callback for each node rather than
1178 // running until the last node.
1179
Austin Schuh8bd96322020-02-13 21:18:22 -08001180 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001181 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1182 << MaybeNodeName(state->event_loop()->node()) << "now "
1183 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001184 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1185 continue;
1186 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001187 // And start computing the start time on the distributed clock now that
1188 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001189 start_time = std::max(
1190 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001191 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001192
Austin Schuh87dd3832021-01-01 23:07:31 -08001193 // TODO(austin): If a node doesn't have a start time, we might not queue
1194 // enough. If this happens, we'll explode with a frozen error eventually.
1195
Austin Schuh2f8fd752020-09-01 22:38:28 -07001196 CHECK_GE(start_time, distributed_clock::epoch())
1197 << ": Hmm, we have a node starting before the start of time. Offset "
1198 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001199
Austin Schuh6f3babe2020-01-26 20:34:50 -08001200 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1201 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001202 // nodes, and also replayed on the other nodes. This may not satisfy all
1203 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001204 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1205 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1206 const Channel *channel = logged_configuration()->channels()->Get(i);
1207 const Node *node = configuration::GetNode(
1208 configuration(), channel->source_node()->string_view());
1209
Austin Schuh8bd96322020-02-13 21:18:22 -08001210 State *state =
1211 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001212
1213 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001214 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001215
1216 event_loop_factory_->DisableForwarding(remapped_channel);
1217 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001218
1219 // If we are replaying a log, we don't want a bunch of redundant messages
1220 // from both the real message bridge and simulated message bridge.
1221 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001222 }
1223
Austin Schuhcde938c2020-02-02 17:30:07 -08001224 // While we are starting the system up, we might be relying on matching data
1225 // to timestamps on log files where the timestamp log file starts before the
1226 // data. In this case, it is reasonable to expect missing data.
1227 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001228 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001229 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001230 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001231 // Now that we are running for real, missing data means that the log file is
1232 // corrupted or went wrong.
1233 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001234
Austin Schuh8bd96322020-02-13 21:18:22 -08001235 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001236 // Make the RT clock be correct before handing it to the user.
1237 if (state->realtime_start_time() != realtime_clock::min_time) {
1238 state->SetRealtimeOffset(state->monotonic_start_time(),
1239 state->realtime_start_time());
1240 }
1241 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1242 << MaybeNodeName(state->event_loop()->node()) << "now "
1243 << state->monotonic_now();
1244 }
1245
1246 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001247 filters_->Start(event_loop_factory);
Austin Schuhaceeb712021-01-06 22:50:00 -08001248 std::fstream s("/tmp/timestamp_noncausal_starttime.csv", s.trunc | s.out);
1249 CHECK(s.is_open());
1250 for (std::unique_ptr<State> &state : states_) {
1251 s << state->event_loop()->node()->name()->string_view() << ", "
1252 << std::setprecision(12) << std::fixed
1253 << chrono::duration<double>(state->monotonic_now().time_since_epoch())
1254 .count()
1255 << "\n";
1256 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001257 }
1258}
1259
Austin Schuh2f8fd752020-09-01 22:38:28 -07001260message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001261 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001262 if (filters_) {
1263 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001264 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001265 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001266}
1267
Austin Schuhe309d2a2019-11-29 13:25:21 -08001268void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001269 State *state =
1270 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1271 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001272
Austin Schuh858c9f32020-08-31 16:56:12 -07001273 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001274
Tyler Chatow67ddb032020-01-12 14:30:04 -08001275 // We don't run timing reports when trying to print out logged data, because
1276 // otherwise we would end up printing out the timing reports themselves...
1277 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001278 event_loop->SkipTimingReport();
1279 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001280
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001281 for (size_t logged_channel_index = 0;
1282 logged_channel_index < logged_configuration()->channels()->size();
1283 ++logged_channel_index) {
1284 const Channel *channel = RemapChannel(
1285 event_loop,
1286 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001287
Austin Schuh2f8fd752020-09-01 22:38:28 -07001288 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -08001289 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001290
1291 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001292
1293 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1294 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001295 // We've got a message which is being forwarded to this node.
1296 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001297 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001298 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001299
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001300 // Delivery timestamps are supposed to be logged back on the source node.
1301 // Configure remote timestamps to be sent.
1302 const bool delivery_time_is_logged =
1303 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1304 channel, event_loop->node(), source_node);
1305
1306 source_state =
1307 states_[configuration::GetNodeIndex(configuration(), source_node)]
1308 .get();
1309
1310 if (delivery_time_is_logged) {
1311 remote_timestamp_sender =
1312 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001313 }
1314 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001315
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001316 state->SetChannel(
1317 logged_channel_index,
1318 configuration::ChannelIndex(event_loop->configuration(), channel),
1319 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1320 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001321 }
1322
Austin Schuh6aa77be2020-02-22 21:06:40 -08001323 // If we didn't find any log files with data in them, we won't ever get a
1324 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001325 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001326 return;
1327 }
1328
Austin Schuh858c9f32020-08-31 16:56:12 -07001329 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001330 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1331 << "at " << state->event_loop()->context().monotonic_event_time
1332 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001333 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001334 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001335 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001336 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001337 event_loop_factory_->Exit();
1338 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001339 return;
1340 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001341
1342 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001343 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001344
Austin Schuhe309d2a2019-11-29 13:25:21 -08001345 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001346 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001347 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001348 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001349 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1350 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001351 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001352 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001353 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001355 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001356 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001357 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001358 << "): " << FlatbufferToJson(state->event_loop()->node())
1359 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001360 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 << state->DebugString();
1362 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001363
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001365 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001366 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001367 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001368 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001369 timestamped_message.data.span().size() != 0u) {
1370 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001371 << ": Got a message without data on channel "
1372 << configuration::CleanedChannelToString(
1373 logged_configuration()->channels()->Get(
1374 timestamped_message.channel_index))
1375 << ". Forwarding entry which was not matched? Use "
1376 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001377
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001379 // Confirm that the message was sent on the sending node before the
1380 // destination node (this node). As a proxy, do this by making sure
1381 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001382 //
1383 // TODO(austin): <= means that the cause message (which we know) could
1384 // happen after the effect even though we know they are at the same
1385 // time. I doubt anyone will notice for a bit, but we should really
1386 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001387 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001388 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -08001389 timestamped_message.monotonic_remote_time,
1390 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001391 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001392 << state->remote_node(timestamped_message.channel_index)
1393 ->name()
1394 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001395 << " while trying to send a message on "
1396 << configuration::CleanedChannelToString(
1397 logged_configuration()->channels()->Get(
1398 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001399 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -08001400 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -08001401 state->monotonic_remote_now(
1402 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001403 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001404 << "Check failed: timestamped_message.monotonic_remote_time < "
1405 "state->monotonic_remote_now(timestamped_message.channel_"
1406 "index) ("
1407 << timestamped_message.monotonic_remote_time << " vs. "
1408 << state->monotonic_remote_now(
1409 timestamped_message.channel_index)
1410 << ") " << state->event_loop()->node()->name()->string_view()
1411 << " to "
1412 << state->remote_node(timestamped_message.channel_index)
1413 ->name()
1414 ->string_view()
1415 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001416 << " ("
1417 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001418 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001419 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001420 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001421 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001422 timestamped_message.channel_index,
1423 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001424 << ") " << state->DebugString();
1425 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001426 }
1427
Austin Schuh15649d62019-12-28 16:36:38 -08001428 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001429 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1430 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001431
Austin Schuh2f8fd752020-09-01 22:38:28 -07001432 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001433 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001434 // TODO(austin): std::move channel_data in and make that efficient in
1435 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001436 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001437 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001438 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001439 // reading the rest of the log file and call it quits. We don't want
1440 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001441 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1442 bool update_time_dummy;
1443 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001444 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001445 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001446 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001447 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001448 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001449 LOG(WARNING)
1450 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001451 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001452 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001453 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001454 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001455 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001456 }
1457
Austin Schuh858c9f32020-08-31 16:56:12 -07001458 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001459 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001460 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1461 << "wakeup for " << next_time << "("
1462 << state->ToDistributedClock(next_time)
1463 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001464 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001465 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001466 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1467 << "No next message, scheduling shutdown";
1468 // Set a timer up immediately after now to die. If we don't do this,
1469 // then the senders waiting on the message we just read will never get
1470 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001471 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001472 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1473 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001474 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001475 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001476
Austin Schuh2f8fd752020-09-01 22:38:28 -07001477 // Once we make this call, the current time changes. So do everything
1478 // which involves time before changing it. That especially includes
1479 // sending the message.
1480 if (update_time) {
1481 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1482 << "updating offsets";
1483
1484 std::vector<aos::monotonic_clock::time_point> before_times;
1485 before_times.resize(states_.size());
1486 std::transform(states_.begin(), states_.end(), before_times.begin(),
1487 [](const std::unique_ptr<State> &state) {
1488 return state->monotonic_now();
1489 });
1490
Austin Schuh2f8fd752020-09-01 22:38:28 -07001491 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1492 << state->monotonic_now();
1493
Austin Schuh2f8fd752020-09-01 22:38:28 -07001494 // TODO(austin): We should be perfect.
1495 const std::chrono::nanoseconds kTolerance{3};
1496 if (!FLAGS_skip_order_validation) {
1497 CHECK_GE(next_time, state->monotonic_now())
Austin Schuh188eabe2020-12-29 23:41:13 -08001498 << ": Time skipped the next event, just sent "
1499 << timestamped_message << ", sending next " << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001500
1501 for (size_t i = 0; i < states_.size(); ++i) {
1502 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1503 << ": Time changed too much on node "
1504 << MaybeNodeName(states_[i]->event_loop()->node());
1505 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1506 << ": Time changed too much on node "
Austin Schuhc9049732020-12-21 22:27:15 -08001507 << MaybeNodeName(states_[i]->event_loop()->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001508 }
1509 } else {
1510 if (next_time < state->monotonic_now()) {
1511 LOG(WARNING) << "Check failed: next_time >= "
1512 "state->monotonic_now() ("
1513 << next_time << " vs. " << state->monotonic_now()
Austin Schuh188eabe2020-12-29 23:41:13 -08001514 << "): Time skipped the next event, just sent "
1515 << timestamped_message << ", sending next "
1516 << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001517 }
1518 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001519 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001520 LOG(WARNING) << "Check failed: "
1521 "states_[i]->monotonic_now() "
1522 ">= before_times[i] - kTolerance ("
1523 << states_[i]->monotonic_now() << " vs. "
1524 << before_times[i] - kTolerance
1525 << ") : Time changed too much on node "
1526 << MaybeNodeName(states_[i]->event_loop()->node());
1527 }
Austin Schuh724032b2020-12-18 22:54:59 -08001528 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001529 LOG(WARNING) << "Check failed: "
1530 "states_[i]->monotonic_now() "
1531 "<= before_times[i] + kTolerance ("
1532 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001533 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001534 << ") : Time changed too much on node "
1535 << MaybeNodeName(states_[i]->event_loop()->node());
1536 }
1537 }
1538 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001539 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001540
1541 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1542 << state->event_loop()->context().monotonic_event_time << " now "
1543 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001544 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001545
Austin Schuh6f3babe2020-01-26 20:34:50 -08001546 ++live_nodes_;
1547
Austin Schuh858c9f32020-08-31 16:56:12 -07001548 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1549 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001550 }
1551}
1552
1553void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001554 // Make sure that things get destroyed in the correct order, rather than
1555 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001556 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001557 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001558 }
Austin Schuh92547522019-12-28 14:33:43 -08001559
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001560 event_loop_factory_unique_ptr_.reset();
1561 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001562}
1563
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001564void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001565 std::string_view add_prefix,
1566 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001567 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1568 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1569 if (channel->name()->str() == name &&
1570 channel->type()->string_view() == type) {
1571 CHECK_EQ(0u, remapped_channels_.count(ii))
1572 << "Already remapped channel "
1573 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001574 RemappedChannel remapped_channel;
1575 remapped_channel.remapped_name =
1576 std::string(add_prefix) + std::string(name);
1577 remapped_channel.new_type = new_type;
1578 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001579 VLOG(1) << "Remapping channel "
1580 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001581 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001582 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001583 return;
1584 }
1585 }
1586 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1587 << type;
1588}
1589
Austin Schuh01b4c352020-09-21 23:09:39 -07001590void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1591 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001592 std::string_view add_prefix,
1593 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001594 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1595 const Channel *remapped_channel =
1596 configuration::GetChannel(logged_configuration(), name, type, "", node);
1597 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1598 << "\", \"type\": \"" << type << "\"}";
1599 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1600 << "\"}";
1601 VLOG(1) << "Remapped "
1602 << aos::configuration::StrippedChannelToString(remapped_channel);
1603
1604 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1605 // we want it to degrade if the heuristics fail to just work.
1606 //
1607 // The easiest way to do this is going to be incredibly specific and verbose.
1608 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1609 // /original/0/spray. Then, create a map from /original/spray to
1610 // /original/0/spray for just the type we were asked for.
1611 if (name != remapped_channel->name()->string_view()) {
1612 MapT new_map;
1613 new_map.match = std::make_unique<ChannelT>();
1614 new_map.match->name = absl::StrCat(add_prefix, name);
1615 new_map.match->type = type;
1616 if (node != nullptr) {
1617 new_map.match->source_node = node->name()->str();
1618 }
1619 new_map.rename = std::make_unique<ChannelT>();
1620 new_map.rename->name =
1621 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1622 maps_.emplace_back(std::move(new_map));
1623 }
1624
1625 const size_t channel_index =
1626 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1627 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1628 << "Already remapped channel "
1629 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001630
1631 RemappedChannel remapped_channel_struct;
1632 remapped_channel_struct.remapped_name =
1633 std::string(add_prefix) +
1634 std::string(remapped_channel->name()->string_view());
1635 remapped_channel_struct.new_type = new_type;
1636 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001637 MakeRemappedConfig();
1638}
1639
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001640void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001641 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001642 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001643 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001644 << ": Can't change the mapping after the events are scheduled.";
1645 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001646 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001647
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001648 // If no remapping occurred and we are using the original config, then there
1649 // is nothing interesting to do here.
1650 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001651 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001652 return;
1653 }
1654 // Config to copy Channel definitions from. Use the specified
1655 // replay_configuration_ if it has been provided.
1656 const Configuration *const base_config = replay_configuration_ == nullptr
1657 ? logged_configuration()
1658 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001659
1660 // Create a config with all the channels, but un-sorted/merged. Collect up
1661 // the schemas while we do this. Call MergeConfiguration to sort everything,
1662 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001663
1664 // This is the builder that we use for the config containing all the new
1665 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001666 flatbuffers::FlatBufferBuilder fbb;
1667 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001668 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001669
1670 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1671 << ": Merging logic needs to be updated when the number of channel "
1672 "fields changes.";
1673
1674 // List of schemas.
1675 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1676 // Make sure our new RemoteMessage schema is in there for old logs without it.
1677 schema_map.insert(std::make_pair(
1678 RemoteMessage::GetFullyQualifiedName(),
1679 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1680 message_bridge::RemoteMessageSchema()))));
1681
1682 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001683 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001684 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001685 base_config, logged_configuration()->channels()->Get(pair.first), "",
1686 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001687 channel_offsets.emplace_back(
1688 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001689 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001690
Austin Schuh0de30f32020-12-06 12:44:28 -08001691 // Now reconstruct the original channels, translating types as needed
1692 for (const Channel *c : *base_config->channels()) {
1693 // Search for a mapping channel.
1694 std::string_view new_type = "";
1695 for (auto &pair : remapped_channels_) {
1696 const Channel *const remapped_channel =
1697 logged_configuration()->channels()->Get(pair.first);
1698 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1699 remapped_channel->type()->string_view() == c->type()->string_view()) {
1700 new_type = pair.second.new_type;
1701 break;
1702 }
1703 }
1704
1705 // Copy everything over.
1706 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1707
1708 // Add the schema if it doesn't exist.
1709 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1710 CHECK(c->has_schema());
1711 schema_map.insert(std::make_pair(c->type()->string_view(),
1712 RecursiveCopyFlatBuffer(c->schema())));
1713 }
1714 }
1715
1716 // The MergeConfiguration API takes a vector, not a map. Convert.
1717 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1718 while (!schema_map.empty()) {
1719 schemas.emplace_back(std::move(schema_map.begin()->second));
1720 schema_map.erase(schema_map.begin());
1721 }
1722
1723 // Create the Configuration containing the new channels that we want to add.
1724 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1725 channels_offset =
1726 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1727
1728 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001729 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001730 if (base_config->maps()) {
1731 for (const Map *map : *base_config->maps()) {
1732 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1733 }
1734 }
1735
1736 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001737 for (const MapT &map : maps_) {
1738 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001739 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001740 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001741 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001742 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001743 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001744 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1745 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001746 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001747 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001748 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001749 match_builder.add_name(match_name_offset);
1750 match_builder.add_type(match_type_offset);
1751 if (!map.match->source_node.empty()) {
1752 match_builder.add_source_node(match_source_node_offset);
1753 }
1754 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1755
Austin Schuh0de30f32020-12-06 12:44:28 -08001756 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001757 rename_builder.add_name(rename_name_offset);
1758 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1759
Austin Schuh0de30f32020-12-06 12:44:28 -08001760 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001761 map_builder.add_match(match_offset);
1762 map_builder.add_rename(rename_offset);
1763 map_offsets.emplace_back(map_builder.Finish());
1764 }
1765
Austin Schuh0de30f32020-12-06 12:44:28 -08001766 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1767 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001768
Austin Schuh0de30f32020-12-06 12:44:28 -08001769 // And copy everything else over.
1770 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1771 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1772
1773 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1774 applications_offset =
1775 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1776
1777 // Now insert everything else in unmodified.
1778 ConfigurationBuilder configuration_builder(fbb);
1779 if (!channels_offset.IsNull()) {
1780 configuration_builder.add_channels(channels_offset);
1781 }
1782 if (!maps_offsets.IsNull()) {
1783 configuration_builder.add_maps(maps_offsets);
1784 }
1785 if (!nodes_offset.IsNull()) {
1786 configuration_builder.add_nodes(nodes_offset);
1787 }
1788 if (!applications_offset.IsNull()) {
1789 configuration_builder.add_applications(applications_offset);
1790 }
1791
1792 if (base_config->has_channel_storage_duration()) {
1793 configuration_builder.add_channel_storage_duration(
1794 base_config->channel_storage_duration());
1795 }
1796
1797 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1798 << ": Merging logic needs to be updated when the number of configuration "
1799 "fields changes.";
1800
1801 fbb.Finish(configuration_builder.Finish());
1802
1803 // Clean it up and return it! By using MergeConfiguration here, we'll
1804 // actually get a deduplicated config for free too.
1805 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1806 configuration::MergeConfiguration(
1807 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1808
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001809 remapped_configuration_buffer_ =
1810 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001811 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001812
1813 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001814
1815 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001816}
1817
Austin Schuh6f3babe2020-01-26 20:34:50 -08001818const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1819 const Channel *channel) {
1820 std::string_view channel_name = channel->name()->string_view();
1821 std::string_view channel_type = channel->type()->string_view();
1822 const int channel_index =
1823 configuration::ChannelIndex(logged_configuration(), channel);
1824 // If the channel is remapped, find the correct channel name to use.
1825 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001826 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001827 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001828 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001829 }
1830
Austin Schuhee711052020-08-24 16:06:09 -07001831 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001832 const Channel *remapped_channel = configuration::GetChannel(
1833 event_loop->configuration(), channel_name, channel_type,
1834 event_loop->name(), event_loop->node());
1835
1836 CHECK(remapped_channel != nullptr)
1837 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1838 << channel_type << "\"} because it is not in the provided configuration.";
1839
1840 return remapped_channel;
1841}
1842
Austin Schuh287d43d2020-12-04 20:19:33 -08001843LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1844 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1845
1846void LogReader::State::AddPeer(State *peer) {
1847 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1848 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1849 }
1850}
Austin Schuh858c9f32020-08-31 16:56:12 -07001851
1852EventLoop *LogReader::State::SetNodeEventLoopFactory(
1853 NodeEventLoopFactory *node_event_loop_factory) {
1854 node_event_loop_factory_ = node_event_loop_factory;
1855 event_loop_unique_ptr_ =
1856 node_event_loop_factory_->MakeEventLoop("log_reader");
1857 return event_loop_unique_ptr_.get();
1858}
1859
1860void LogReader::State::SetChannelCount(size_t count) {
1861 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001862 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001863 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001864 channel_source_state_.resize(count);
1865 factory_channel_index_.resize(count);
1866 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001867}
1868
1869void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001870 size_t logged_channel_index, size_t factory_channel_index,
1871 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001872 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001873 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001874 channels_[logged_channel_index] = std::move(sender);
1875 filters_[logged_channel_index] = filter;
1876 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1877
1878 if (source_state) {
1879 channel_source_state_[logged_channel_index] = source_state;
1880
1881 if (remote_timestamp_sender != nullptr) {
1882 source_state->queue_index_map_[logged_channel_index] =
1883 std::make_unique<std::vector<State::SentTimestamp>>();
1884 }
1885 }
1886
1887 factory_channel_index_[logged_channel_index] = factory_channel_index;
1888}
1889
Austin Schuh287d43d2020-12-04 20:19:33 -08001890bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1891 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001892 uint32_t remote_queue_index = 0xffffffff;
1893
Austin Schuh287d43d2020-12-04 20:19:33 -08001894 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
1895 std::vector<SentTimestamp> *queue_index_map = CHECK_NOTNULL(
1896 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1897 ->queue_index_map_[timestamped_message.channel_index]
1898 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001899
1900 SentTimestamp search;
Austin Schuh287d43d2020-12-04 20:19:33 -08001901 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
1902 search.realtime_event_time = timestamped_message.realtime_remote_time;
1903 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001904
1905 // Find the sent time if available.
1906 auto element = std::lower_bound(
1907 queue_index_map->begin(), queue_index_map->end(), search,
1908 [](SentTimestamp a, SentTimestamp b) {
1909 if (b.monotonic_event_time < a.monotonic_event_time) {
1910 return false;
1911 }
1912 if (b.monotonic_event_time > a.monotonic_event_time) {
1913 return true;
1914 }
1915
1916 if (b.queue_index < a.queue_index) {
1917 return false;
1918 }
1919 if (b.queue_index > a.queue_index) {
1920 return true;
1921 }
1922
1923 CHECK_EQ(a.realtime_event_time, b.realtime_event_time);
1924 return false;
1925 });
1926
1927 // TODO(austin): Be a bit more principled here, but we will want to do that
1928 // after the logger rewrite. We hit this when one node finishes, but the
1929 // other node isn't done yet. So there is no send time, but there is a
1930 // receive time.
1931 if (element != queue_index_map->end()) {
1932 CHECK_EQ(element->monotonic_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001933 timestamped_message.monotonic_remote_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001934 CHECK_EQ(element->realtime_event_time,
Austin Schuh287d43d2020-12-04 20:19:33 -08001935 timestamped_message.realtime_remote_time);
1936 CHECK_EQ(element->queue_index, timestamped_message.remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001937
1938 remote_queue_index = element->actual_queue_index;
1939 }
1940 }
1941
1942 // Send! Use the replayed queue index here instead of the logged queue index
1943 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001944 const bool sent = sender->Send(
1945 timestamped_message.data.message().data()->Data(),
1946 timestamped_message.data.message().data()->size(),
1947 timestamped_message.monotonic_remote_time,
1948 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001949 if (!sent) return false;
1950
Austin Schuh287d43d2020-12-04 20:19:33 -08001951 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001952 SentTimestamp timestamp;
Austin Schuh287d43d2020-12-04 20:19:33 -08001953 timestamp.monotonic_event_time = timestamped_message.monotonic_event_time;
1954 timestamp.realtime_event_time = timestamped_message.realtime_event_time;
1955 timestamp.queue_index = timestamped_message.queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001956 timestamp.actual_queue_index = sender->sent_queue_index();
Austin Schuh287d43d2020-12-04 20:19:33 -08001957 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1958 timestamp);
1959 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1960 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001961 flatbuffers::FlatBufferBuilder fbb;
1962 fbb.ForceDefaults(true);
Austin Schuh315b96b2020-12-11 21:21:12 -08001963 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
Austin Schuh969cd602021-01-03 00:09:45 -08001964 fbb.CreateString(event_loop_->boot_uuid().string_view());
Austin Schuh315b96b2020-12-11 21:21:12 -08001965
Austin Schuh969cd602021-01-03 00:09:45 -08001966 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001967
1968 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001969 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001970
1971 // Swap the remote and sent metrics. They are from the sender's
1972 // perspective, not the receiver's perspective.
1973 message_header_builder.add_monotonic_sent_time(
1974 sender->monotonic_sent_time().time_since_epoch().count());
1975 message_header_builder.add_realtime_sent_time(
1976 sender->realtime_sent_time().time_since_epoch().count());
1977 message_header_builder.add_queue_index(sender->sent_queue_index());
1978
1979 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001980 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001981 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001982 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001983
1984 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001985 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001986
Austin Schuh969cd602021-01-03 00:09:45 -08001987 fbb.Finish(message_header_builder.Finish());
1988
1989 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1990 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
1991 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001992 }
1993
1994 return true;
1995}
1996
Austin Schuh969cd602021-01-03 00:09:45 -08001997LogReader::RemoteMessageSender::RemoteMessageSender(
1998 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
1999 : event_loop_(event_loop),
2000 sender_(std::move(sender)),
2001 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2002
2003void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2004 if (remote_timestamps_.empty()) {
2005 CHECK_NOTNULL(timer_);
2006 timer_->Disable();
2007 scheduled_time_ = monotonic_clock::min_time;
2008 return;
2009 }
2010
2011 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2012 CHECK_NOTNULL(timer_);
2013 timer_->Setup(
2014 remote_timestamps_.front().monotonic_timestamp_time);
2015 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
2016 }
2017}
2018
2019void LogReader::RemoteMessageSender::Send(
2020 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
2021 monotonic_clock::time_point monotonic_timestamp_time) {
2022 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
2023 // resend the timestamp at the correct time, or we don't and can send it
2024 // immediately.
2025 if (monotonic_timestamp_time == monotonic_clock::min_time) {
2026 CHECK(remote_timestamps_.empty())
2027 << ": Unsupported mix of timestamps and no timestamps.";
2028 sender_.Send(std::move(remote_message));
2029 } else {
2030 remote_timestamps_.emplace_back(std::move(remote_message),
2031 monotonic_timestamp_time);
2032 ScheduleTimestamp();
2033 }
2034}
2035
2036void LogReader::RemoteMessageSender::SendTimestamp() {
2037 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_);
2038 CHECK(!remote_timestamps_.empty());
2039
2040 // Send out all timestamps at the currently scheduled time.
2041 while (remote_timestamps_.front().monotonic_timestamp_time ==
2042 scheduled_time_) {
2043 sender_.Send(std::move(remote_timestamps_.front().remote_message));
2044 remote_timestamps_.pop_front();
2045 if (remote_timestamps_.empty()) {
2046 break;
2047 }
2048 }
2049 scheduled_time_ = monotonic_clock::min_time;
2050
2051 ScheduleTimestamp();
2052}
2053
2054LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002055 const Node *delivered_node) {
2056 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2057
2058 if (sender == remote_timestamp_senders_map_.end()) {
Austin Schuh969cd602021-01-03 00:09:45 -08002059 sender =
2060 remote_timestamp_senders_map_
2061 .emplace(delivered_node,
2062 std::make_unique<RemoteMessageSender>(
2063 event_loop()->MakeSender<RemoteMessage>(absl::StrCat(
2064 "/aos/remote_timestamps/",
2065 delivered_node->name()->string_view())),
2066 event_loop()))
2067 .first;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002068 }
2069
Austin Schuh969cd602021-01-03 00:09:45 -08002070 return sender->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002071}
2072
Austin Schuh188eabe2020-12-29 23:41:13 -08002073const TimestampedMessage &LogReader::State::PeekOldest() {
2074 return std::get<0>(sorted_messages_.front());
2075}
2076
Austin Schuh287d43d2020-12-04 20:19:33 -08002077TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002078 CHECK_GT(sorted_messages_.size(), 0u);
2079
Austin Schuh287d43d2020-12-04 20:19:33 -08002080 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002081 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002082 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002083 << std::get<0>(result).monotonic_event_time;
2084 sorted_messages_.pop_front();
2085 SeedSortedMessages();
2086
Austin Schuh287d43d2020-12-04 20:19:33 -08002087 if (std::get<1>(result) != nullptr) {
2088 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002089 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2090 } else {
2091 *update_time = false;
2092 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002093 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002094}
2095
2096monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2097 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002098 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002099 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2100 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2101 }
2102
Austin Schuh287d43d2020-12-04 20:19:33 -08002103 TimestampedMessage *m =
2104 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2105 if (m == nullptr) {
2106 return monotonic_clock::max_time;
2107 }
2108 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002109}
2110
2111void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002112 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002113 const aos::monotonic_clock::time_point end_queue_time =
2114 (sorted_messages_.size() > 0
2115 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002116 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002117 chrono::duration_cast<chrono::seconds>(
2118 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002119
2120 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002121 TimestampedMessage *m = timestamp_mapper_->Front();
2122 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002123 return;
2124 }
2125 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002126 // Stop placing sorted messages on the list once we have
2127 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2128 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002129 if (end_queue_time <
2130 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2131 return;
2132 }
2133 }
2134
Austin Schuh2f8fd752020-09-01 22:38:28 -07002135 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2136
Austin Schuh287d43d2020-12-04 20:19:33 -08002137 TimestampedMessage timestamped_message = std::move(*m);
2138 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002139
Austin Schuh2f8fd752020-09-01 22:38:28 -07002140 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002141 if (timestamped_message.monotonic_remote_time !=
2142 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002143 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002144 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002145
2146 CHECK(filter != nullptr);
2147
2148 // Call the correct method depending on if we are the forward or
2149 // reverse direction here.
2150 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002151 timestamped_message.monotonic_event_time,
2152 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002153 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002154 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002155 }
2156}
2157
2158void LogReader::State::Deregister() {
2159 for (size_t i = 0; i < channels_.size(); ++i) {
2160 channels_[i].reset();
2161 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002162 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002163 event_loop_unique_ptr_.reset();
2164 event_loop_ = nullptr;
2165 timer_handler_ = nullptr;
2166 node_event_loop_factory_ = nullptr;
2167}
2168
Austin Schuhe309d2a2019-11-29 13:25:21 -08002169} // namespace logger
2170} // namespace aos