blob: 7f08f7a344a25f2ebb4afd625563970175b20f96 [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.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001001 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
1002 // careful about updating the config, but there are fewer and fewer logs
1003 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -08001004 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
1005 "aos.message_bridge.RemoteMessage");
1006 } else {
1007 CHECK(HasChannel<RemoteMessage>(channel, node))
1008 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
1009 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
1010 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001011 // Only bother to remap if there's something on the channel. We can
1012 // tell if the channel was marked NOT_LOGGED or not. This makes the
1013 // config not change un-necesarily when we replay a log with NOT_LOGGED
1014 // messages.
1015 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
1016 RemapLoggedChannel<RemoteMessage>(channel, node);
1017 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001018 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001019 }
1020 }
1021
Austin Schuh6aa77be2020-02-22 21:06:40 -08001022 if (replay_configuration) {
1023 CHECK_EQ(configuration::MultiNode(configuration()),
1024 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001025 << ": Log file and replay config need to both be multi or single "
1026 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -08001027 }
1028
Austin Schuh6f3babe2020-01-26 20:34:50 -08001029 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001030 states_.emplace_back(std::make_unique<State>(
1031 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -08001032 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001033 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -07001034 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -08001035 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -07001036 << ": Log file and replay config need to have matching nodes "
1037 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001038 for (const Node *node : *logged_configuration()->nodes()) {
1039 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001040 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
1041 << " in logged config that is not present in the replay "
1042 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001043 }
1044 }
Austin Schuh6aa77be2020-02-22 21:06:40 -08001045 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001046 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001047 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001048}
1049
Austin Schuh6aa77be2020-02-22 21:06:40 -08001050LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -07001051 if (event_loop_factory_unique_ptr_) {
1052 Deregister();
1053 } else if (event_loop_factory_ != nullptr) {
1054 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
1055 "is destroyed";
1056 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001057 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1058 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001059 if (remapped_configuration_buffer_) {
1060 remapped_configuration_buffer_->Wipe();
1061 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001062}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001063
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001064const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001065 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001066}
1067
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001068const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001069 return remapped_configuration_;
1070}
1071
Austin Schuh6f3babe2020-01-26 20:34:50 -08001072std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001073 // Because the Node pointer will only be valid if it actually points to
1074 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001075 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001076 //
1077 // Also, note, that when ever a map is changed, the nodes in here are
1078 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001079 CHECK(remapped_configuration_ != nullptr)
1080 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001081 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001082}
Austin Schuh15649d62019-12-28 16:36:38 -08001083
Austin Schuh11d43732020-09-21 17:28:30 -07001084monotonic_clock::time_point LogReader::monotonic_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->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001091}
1092
Austin Schuh11d43732020-09-21 17:28:30 -07001093realtime_clock::time_point LogReader::realtime_start_time(
1094 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001095 State *state =
1096 states_[configuration::GetNodeIndex(configuration(), node)].get();
1097 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1098
Austin Schuh858c9f32020-08-31 16:56:12 -07001099 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001100}
1101
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001102void LogReader::Register() {
1103 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001104 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001105 Register(event_loop_factory_unique_ptr_.get());
1106}
1107
Austin Schuh92547522019-12-28 14:33:43 -08001108void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001109 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001110 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001111 filters_ =
1112 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuh87dd3832021-01-01 23:07:31 -08001113 event_loop_factory_, logged_configuration(),
1114 FLAGS_skip_order_validation);
Austin Schuh92547522019-12-28 14:33:43 -08001115
Brian Silvermand90905f2020-09-23 14:42:56 -07001116 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001117 const size_t node_index =
1118 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001119 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1120 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001121
1122 // Confirm that all the parts are from the same boot if there are enough
1123 // parts to not be from the same boot.
1124 if (filtered_parts.size() > 1u) {
1125 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1126 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1127 filtered_parts[0].source_boot_uuid)
1128 << ": Found parts from different boots "
1129 << LogFileVectorToString(log_files_);
1130 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001131 if (!filtered_parts[0].source_boot_uuid.empty()) {
1132 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
1133 filtered_parts[0].source_boot_uuid);
1134 }
Austin Schuh315b96b2020-12-11 21:21:12 -08001135 }
1136
Austin Schuh287d43d2020-12-04 20:19:33 -08001137 states_[node_index] = std::make_unique<State>(
1138 filtered_parts.size() == 0u
1139 ? nullptr
1140 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001141 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001142 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001143 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001144
1145 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001146 }
Austin Schuh87dd3832021-01-01 23:07:31 -08001147 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001148
Austin Schuh287d43d2020-12-04 20:19:33 -08001149 for (const Node *node : configuration::GetNodes(configuration())) {
1150 const size_t node_index =
1151 configuration::GetNodeIndex(configuration(), node);
1152 State *state = states_[node_index].get();
1153 for (const Node *other_node : configuration::GetNodes(configuration())) {
1154 const size_t other_node_index =
1155 configuration::GetNodeIndex(configuration(), other_node);
1156 State *other_state = states_[other_node_index].get();
1157 if (other_state != state) {
1158 state->AddPeer(other_state);
1159 }
1160 }
1161 }
1162
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001163 // Register after making all the State objects so we can build references
1164 // between them.
1165 for (const Node *node : configuration::GetNodes(configuration())) {
1166 const size_t node_index =
1167 configuration::GetNodeIndex(configuration(), node);
1168 State *state = states_[node_index].get();
1169
1170 Register(state->event_loop());
1171 }
1172
James Kuszmaul46d82582020-05-09 19:50:09 -07001173 if (live_nodes_ == 0) {
1174 LOG(FATAL)
1175 << "Don't have logs from any of the nodes in the replay config--are "
1176 "you sure that the replay config matches the original config?";
1177 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001178
Austin Schuh87dd3832021-01-01 23:07:31 -08001179 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001180
Austin Schuh858c9f32020-08-31 16:56:12 -07001181 for (std::unique_ptr<State> &state : states_) {
1182 state->SeedSortedMessages();
1183 }
1184
Austin Schuh2f8fd752020-09-01 22:38:28 -07001185 // We want to start the log file at the last start time of the log files
1186 // from all the nodes. Compute how long each node's simulation needs to run
1187 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001188 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001189
Austin Schuh2f8fd752020-09-01 22:38:28 -07001190 // TODO(austin): We want an "OnStart" callback for each node rather than
1191 // running until the last node.
1192
Austin Schuh8bd96322020-02-13 21:18:22 -08001193 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001194 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1195 << MaybeNodeName(state->event_loop()->node()) << "now "
1196 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001197 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1198 continue;
1199 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001200 // And start computing the start time on the distributed clock now that
1201 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001202 start_time = std::max(
1203 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001204 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205
Austin Schuh87dd3832021-01-01 23:07:31 -08001206 // TODO(austin): If a node doesn't have a start time, we might not queue
1207 // enough. If this happens, we'll explode with a frozen error eventually.
1208
Austin Schuh2f8fd752020-09-01 22:38:28 -07001209 CHECK_GE(start_time, distributed_clock::epoch())
1210 << ": Hmm, we have a node starting before the start of time. Offset "
1211 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001212
Austin Schuh6f3babe2020-01-26 20:34:50 -08001213 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1214 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001215 // nodes, and also replayed on the other nodes. This may not satisfy all
1216 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001217 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1218 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1219 const Channel *channel = logged_configuration()->channels()->Get(i);
1220 const Node *node = configuration::GetNode(
1221 configuration(), channel->source_node()->string_view());
1222
Austin Schuh8bd96322020-02-13 21:18:22 -08001223 State *state =
1224 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225
1226 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001227 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001228
1229 event_loop_factory_->DisableForwarding(remapped_channel);
1230 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001231
1232 // If we are replaying a log, we don't want a bunch of redundant messages
1233 // from both the real message bridge and simulated message bridge.
1234 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001235 }
1236
Austin Schuhcde938c2020-02-02 17:30:07 -08001237 // While we are starting the system up, we might be relying on matching data
1238 // to timestamps on log files where the timestamp log file starts before the
1239 // data. In this case, it is reasonable to expect missing data.
1240 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001241 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001242 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001243 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001244 // Now that we are running for real, missing data means that the log file is
1245 // corrupted or went wrong.
1246 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001247
Austin Schuh8bd96322020-02-13 21:18:22 -08001248 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001249 // Make the RT clock be correct before handing it to the user.
1250 if (state->realtime_start_time() != realtime_clock::min_time) {
1251 state->SetRealtimeOffset(state->monotonic_start_time(),
1252 state->realtime_start_time());
1253 }
1254 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1255 << MaybeNodeName(state->event_loop()->node()) << "now "
1256 << state->monotonic_now();
1257 }
1258
1259 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001260 filters_->Start(event_loop_factory);
Austin Schuhaceeb712021-01-06 22:50:00 -08001261 std::fstream s("/tmp/timestamp_noncausal_starttime.csv", s.trunc | s.out);
1262 CHECK(s.is_open());
1263 for (std::unique_ptr<State> &state : states_) {
1264 s << state->event_loop()->node()->name()->string_view() << ", "
1265 << std::setprecision(12) << std::fixed
1266 << chrono::duration<double>(state->monotonic_now().time_since_epoch())
1267 .count()
1268 << "\n";
1269 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001270 }
1271}
1272
Austin Schuh2f8fd752020-09-01 22:38:28 -07001273message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001274 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001275 if (filters_) {
1276 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001277 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001278 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001279}
1280
Austin Schuhe309d2a2019-11-29 13:25:21 -08001281void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001282 State *state =
1283 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1284 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001285
Austin Schuh858c9f32020-08-31 16:56:12 -07001286 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001287
Tyler Chatow67ddb032020-01-12 14:30:04 -08001288 // We don't run timing reports when trying to print out logged data, because
1289 // otherwise we would end up printing out the timing reports themselves...
1290 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001291 event_loop->SkipTimingReport();
1292 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001293
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001294 for (size_t logged_channel_index = 0;
1295 logged_channel_index < logged_configuration()->channels()->size();
1296 ++logged_channel_index) {
1297 const Channel *channel = RemapChannel(
1298 event_loop,
1299 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001300
Austin Schuh2f8fd752020-09-01 22:38:28 -07001301 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -08001302 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001303
1304 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001305
1306 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1307 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001308 // We've got a message which is being forwarded to this node.
1309 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001310 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001311 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001312
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001313 // Delivery timestamps are supposed to be logged back on the source node.
1314 // Configure remote timestamps to be sent.
1315 const bool delivery_time_is_logged =
1316 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1317 channel, event_loop->node(), source_node);
1318
1319 source_state =
1320 states_[configuration::GetNodeIndex(configuration(), source_node)]
1321 .get();
1322
1323 if (delivery_time_is_logged) {
1324 remote_timestamp_sender =
1325 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001326 }
1327 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001328
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001329 state->SetChannel(
1330 logged_channel_index,
1331 configuration::ChannelIndex(event_loop->configuration(), channel),
1332 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1333 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001334 }
1335
Austin Schuh6aa77be2020-02-22 21:06:40 -08001336 // If we didn't find any log files with data in them, we won't ever get a
1337 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001338 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001339 return;
1340 }
1341
Austin Schuh858c9f32020-08-31 16:56:12 -07001342 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001343 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1344 << "at " << state->event_loop()->context().monotonic_event_time
1345 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001346 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001347 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001348 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001349 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001350 event_loop_factory_->Exit();
1351 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001352 return;
1353 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354
1355 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001356 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001357
Austin Schuhe309d2a2019-11-29 13:25:21 -08001358 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001359 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001360 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001361 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001362 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1363 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001365 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001366 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001367 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001368 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001369 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001370 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001371 << "): " << FlatbufferToJson(state->event_loop()->node())
1372 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001373 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001374 << state->DebugString();
1375 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001376
Austin Schuh287d43d2020-12-04 20:19:33 -08001377 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001378 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001379 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001380 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001381 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001382 timestamped_message.data.span().size() != 0u) {
1383 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001384 << ": Got a message without data on channel "
1385 << configuration::CleanedChannelToString(
1386 logged_configuration()->channels()->Get(
1387 timestamped_message.channel_index))
1388 << ". Forwarding entry which was not matched? Use "
1389 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001390
Austin Schuh2f8fd752020-09-01 22:38:28 -07001391 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001392 // Confirm that the message was sent on the sending node before the
1393 // destination node (this node). As a proxy, do this by making sure
1394 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001395 //
1396 // TODO(austin): <= means that the cause message (which we know) could
1397 // happen after the effect even though we know they are at the same
1398 // time. I doubt anyone will notice for a bit, but we should really
1399 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001400 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001401 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -08001402 timestamped_message.monotonic_remote_time,
1403 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001404 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001405 << state->remote_node(timestamped_message.channel_index)
1406 ->name()
1407 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001408 << " while trying to send a message on "
1409 << configuration::CleanedChannelToString(
1410 logged_configuration()->channels()->Get(
1411 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001412 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -08001413 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -08001414 state->monotonic_remote_now(
1415 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001416 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001417 << "Check failed: timestamped_message.monotonic_remote_time < "
1418 "state->monotonic_remote_now(timestamped_message.channel_"
1419 "index) ("
1420 << timestamped_message.monotonic_remote_time << " vs. "
1421 << state->monotonic_remote_now(
1422 timestamped_message.channel_index)
1423 << ") " << state->event_loop()->node()->name()->string_view()
1424 << " to "
1425 << state->remote_node(timestamped_message.channel_index)
1426 ->name()
1427 ->string_view()
1428 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001429 << " ("
1430 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001431 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001432 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001433 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001434 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001435 timestamped_message.channel_index,
1436 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001437 << ") " << state->DebugString();
1438 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001439 }
1440
Austin Schuh15649d62019-12-28 16:36:38 -08001441 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001442 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1443 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001444
Austin Schuh2f8fd752020-09-01 22:38:28 -07001445 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001446 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001447 // TODO(austin): std::move channel_data in and make that efficient in
1448 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001449 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001450 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001451 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001452 // reading the rest of the log file and call it quits. We don't want
1453 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001454 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1455 bool update_time_dummy;
1456 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001457 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001458 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001459 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001460 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001461 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001462 LOG(WARNING)
1463 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001464 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001465 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001466 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001467 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001468 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001469 }
1470
Austin Schuh858c9f32020-08-31 16:56:12 -07001471 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001472 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001473 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1474 << "wakeup for " << next_time << "("
1475 << state->ToDistributedClock(next_time)
1476 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001477 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001478 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001479 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1480 << "No next message, scheduling shutdown";
1481 // Set a timer up immediately after now to die. If we don't do this,
1482 // then the senders waiting on the message we just read will never get
1483 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001484 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001485 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1486 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001487 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001488 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001489
Austin Schuh2f8fd752020-09-01 22:38:28 -07001490 // Once we make this call, the current time changes. So do everything
1491 // which involves time before changing it. That especially includes
1492 // sending the message.
1493 if (update_time) {
1494 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1495 << "updating offsets";
1496
1497 std::vector<aos::monotonic_clock::time_point> before_times;
1498 before_times.resize(states_.size());
1499 std::transform(states_.begin(), states_.end(), before_times.begin(),
1500 [](const std::unique_ptr<State> &state) {
1501 return state->monotonic_now();
1502 });
1503
Austin Schuh2f8fd752020-09-01 22:38:28 -07001504 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1505 << state->monotonic_now();
1506
Austin Schuh2f8fd752020-09-01 22:38:28 -07001507 // TODO(austin): We should be perfect.
1508 const std::chrono::nanoseconds kTolerance{3};
1509 if (!FLAGS_skip_order_validation) {
1510 CHECK_GE(next_time, state->monotonic_now())
Austin Schuh188eabe2020-12-29 23:41:13 -08001511 << ": Time skipped the next event, just sent "
1512 << timestamped_message << ", sending next " << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001513
1514 for (size_t i = 0; i < states_.size(); ++i) {
1515 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1516 << ": Time changed too much on node "
1517 << MaybeNodeName(states_[i]->event_loop()->node());
1518 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1519 << ": Time changed too much on node "
Austin Schuhc9049732020-12-21 22:27:15 -08001520 << MaybeNodeName(states_[i]->event_loop()->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001521 }
1522 } else {
1523 if (next_time < state->monotonic_now()) {
1524 LOG(WARNING) << "Check failed: next_time >= "
1525 "state->monotonic_now() ("
1526 << next_time << " vs. " << state->monotonic_now()
Austin Schuh188eabe2020-12-29 23:41:13 -08001527 << "): Time skipped the next event, just sent "
1528 << timestamped_message << ", sending next "
1529 << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001530 }
1531 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001532 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001533 LOG(WARNING) << "Check failed: "
1534 "states_[i]->monotonic_now() "
1535 ">= before_times[i] - kTolerance ("
1536 << states_[i]->monotonic_now() << " vs. "
1537 << before_times[i] - kTolerance
1538 << ") : Time changed too much on node "
1539 << MaybeNodeName(states_[i]->event_loop()->node());
1540 }
Austin Schuh724032b2020-12-18 22:54:59 -08001541 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001542 LOG(WARNING) << "Check failed: "
1543 "states_[i]->monotonic_now() "
1544 "<= before_times[i] + kTolerance ("
1545 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001546 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001547 << ") : Time changed too much on node "
1548 << MaybeNodeName(states_[i]->event_loop()->node());
1549 }
1550 }
1551 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001552 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001553
1554 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1555 << state->event_loop()->context().monotonic_event_time << " now "
1556 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001557 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001558
Austin Schuh6f3babe2020-01-26 20:34:50 -08001559 ++live_nodes_;
1560
Austin Schuh858c9f32020-08-31 16:56:12 -07001561 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1562 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001563 }
1564}
1565
1566void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001567 // Make sure that things get destroyed in the correct order, rather than
1568 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001569 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001570 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001571 }
Austin Schuh92547522019-12-28 14:33:43 -08001572
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001573 event_loop_factory_unique_ptr_.reset();
1574 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001575}
1576
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001577void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001578 std::string_view add_prefix,
1579 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001580 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1581 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1582 if (channel->name()->str() == name &&
1583 channel->type()->string_view() == type) {
1584 CHECK_EQ(0u, remapped_channels_.count(ii))
1585 << "Already remapped channel "
1586 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001587 RemappedChannel remapped_channel;
1588 remapped_channel.remapped_name =
1589 std::string(add_prefix) + std::string(name);
1590 remapped_channel.new_type = new_type;
1591 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001592 VLOG(1) << "Remapping channel "
1593 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001594 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001595 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001596 return;
1597 }
1598 }
1599 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1600 << type;
1601}
1602
Austin Schuh01b4c352020-09-21 23:09:39 -07001603void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1604 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001605 std::string_view add_prefix,
1606 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001607 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1608 const Channel *remapped_channel =
1609 configuration::GetChannel(logged_configuration(), name, type, "", node);
1610 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1611 << "\", \"type\": \"" << type << "\"}";
1612 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1613 << "\"}";
1614 VLOG(1) << "Remapped "
1615 << aos::configuration::StrippedChannelToString(remapped_channel);
1616
1617 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1618 // we want it to degrade if the heuristics fail to just work.
1619 //
1620 // The easiest way to do this is going to be incredibly specific and verbose.
1621 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1622 // /original/0/spray. Then, create a map from /original/spray to
1623 // /original/0/spray for just the type we were asked for.
1624 if (name != remapped_channel->name()->string_view()) {
1625 MapT new_map;
1626 new_map.match = std::make_unique<ChannelT>();
1627 new_map.match->name = absl::StrCat(add_prefix, name);
1628 new_map.match->type = type;
1629 if (node != nullptr) {
1630 new_map.match->source_node = node->name()->str();
1631 }
1632 new_map.rename = std::make_unique<ChannelT>();
1633 new_map.rename->name =
1634 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1635 maps_.emplace_back(std::move(new_map));
1636 }
1637
1638 const size_t channel_index =
1639 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1640 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1641 << "Already remapped channel "
1642 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001643
1644 RemappedChannel remapped_channel_struct;
1645 remapped_channel_struct.remapped_name =
1646 std::string(add_prefix) +
1647 std::string(remapped_channel->name()->string_view());
1648 remapped_channel_struct.new_type = new_type;
1649 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001650 MakeRemappedConfig();
1651}
1652
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001653void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001654 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001655 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001656 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001657 << ": Can't change the mapping after the events are scheduled.";
1658 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001659 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001660
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001661 // If no remapping occurred and we are using the original config, then there
1662 // is nothing interesting to do here.
1663 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001664 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001665 return;
1666 }
1667 // Config to copy Channel definitions from. Use the specified
1668 // replay_configuration_ if it has been provided.
1669 const Configuration *const base_config = replay_configuration_ == nullptr
1670 ? logged_configuration()
1671 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001672
1673 // Create a config with all the channels, but un-sorted/merged. Collect up
1674 // the schemas while we do this. Call MergeConfiguration to sort everything,
1675 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001676
1677 // This is the builder that we use for the config containing all the new
1678 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001679 flatbuffers::FlatBufferBuilder fbb;
1680 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001681 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001682
1683 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1684 << ": Merging logic needs to be updated when the number of channel "
1685 "fields changes.";
1686
1687 // List of schemas.
1688 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1689 // Make sure our new RemoteMessage schema is in there for old logs without it.
1690 schema_map.insert(std::make_pair(
1691 RemoteMessage::GetFullyQualifiedName(),
1692 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1693 message_bridge::RemoteMessageSchema()))));
1694
1695 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001696 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001697 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001698 base_config, logged_configuration()->channels()->Get(pair.first), "",
1699 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001700 channel_offsets.emplace_back(
1701 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001702 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001703
Austin Schuh0de30f32020-12-06 12:44:28 -08001704 // Now reconstruct the original channels, translating types as needed
1705 for (const Channel *c : *base_config->channels()) {
1706 // Search for a mapping channel.
1707 std::string_view new_type = "";
1708 for (auto &pair : remapped_channels_) {
1709 const Channel *const remapped_channel =
1710 logged_configuration()->channels()->Get(pair.first);
1711 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1712 remapped_channel->type()->string_view() == c->type()->string_view()) {
1713 new_type = pair.second.new_type;
1714 break;
1715 }
1716 }
1717
1718 // Copy everything over.
1719 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1720
1721 // Add the schema if it doesn't exist.
1722 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1723 CHECK(c->has_schema());
1724 schema_map.insert(std::make_pair(c->type()->string_view(),
1725 RecursiveCopyFlatBuffer(c->schema())));
1726 }
1727 }
1728
1729 // The MergeConfiguration API takes a vector, not a map. Convert.
1730 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1731 while (!schema_map.empty()) {
1732 schemas.emplace_back(std::move(schema_map.begin()->second));
1733 schema_map.erase(schema_map.begin());
1734 }
1735
1736 // Create the Configuration containing the new channels that we want to add.
1737 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1738 channels_offset =
1739 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1740
1741 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001742 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001743 if (base_config->maps()) {
1744 for (const Map *map : *base_config->maps()) {
1745 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1746 }
1747 }
1748
1749 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001750 for (const MapT &map : maps_) {
1751 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001752 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001753 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001754 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001755 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001756 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001757 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1758 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001759 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001760 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001761 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001762 match_builder.add_name(match_name_offset);
1763 match_builder.add_type(match_type_offset);
1764 if (!map.match->source_node.empty()) {
1765 match_builder.add_source_node(match_source_node_offset);
1766 }
1767 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1768
Austin Schuh0de30f32020-12-06 12:44:28 -08001769 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001770 rename_builder.add_name(rename_name_offset);
1771 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1772
Austin Schuh0de30f32020-12-06 12:44:28 -08001773 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001774 map_builder.add_match(match_offset);
1775 map_builder.add_rename(rename_offset);
1776 map_offsets.emplace_back(map_builder.Finish());
1777 }
1778
Austin Schuh0de30f32020-12-06 12:44:28 -08001779 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1780 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001781
Austin Schuh0de30f32020-12-06 12:44:28 -08001782 // And copy everything else over.
1783 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1784 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1785
1786 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1787 applications_offset =
1788 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1789
1790 // Now insert everything else in unmodified.
1791 ConfigurationBuilder configuration_builder(fbb);
1792 if (!channels_offset.IsNull()) {
1793 configuration_builder.add_channels(channels_offset);
1794 }
1795 if (!maps_offsets.IsNull()) {
1796 configuration_builder.add_maps(maps_offsets);
1797 }
1798 if (!nodes_offset.IsNull()) {
1799 configuration_builder.add_nodes(nodes_offset);
1800 }
1801 if (!applications_offset.IsNull()) {
1802 configuration_builder.add_applications(applications_offset);
1803 }
1804
1805 if (base_config->has_channel_storage_duration()) {
1806 configuration_builder.add_channel_storage_duration(
1807 base_config->channel_storage_duration());
1808 }
1809
1810 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1811 << ": Merging logic needs to be updated when the number of configuration "
1812 "fields changes.";
1813
1814 fbb.Finish(configuration_builder.Finish());
1815
1816 // Clean it up and return it! By using MergeConfiguration here, we'll
1817 // actually get a deduplicated config for free too.
1818 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1819 configuration::MergeConfiguration(
1820 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1821
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001822 remapped_configuration_buffer_ =
1823 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001824 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001825
1826 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001827
1828 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001829}
1830
Austin Schuh6f3babe2020-01-26 20:34:50 -08001831const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1832 const Channel *channel) {
1833 std::string_view channel_name = channel->name()->string_view();
1834 std::string_view channel_type = channel->type()->string_view();
1835 const int channel_index =
1836 configuration::ChannelIndex(logged_configuration(), channel);
1837 // If the channel is remapped, find the correct channel name to use.
1838 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001839 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001840 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001841 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001842 }
1843
Austin Schuhee711052020-08-24 16:06:09 -07001844 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001845 const Channel *remapped_channel = configuration::GetChannel(
1846 event_loop->configuration(), channel_name, channel_type,
1847 event_loop->name(), event_loop->node());
1848
1849 CHECK(remapped_channel != nullptr)
1850 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1851 << channel_type << "\"} because it is not in the provided configuration.";
1852
1853 return remapped_channel;
1854}
1855
Austin Schuh287d43d2020-12-04 20:19:33 -08001856LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1857 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1858
1859void LogReader::State::AddPeer(State *peer) {
1860 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1861 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1862 }
1863}
Austin Schuh858c9f32020-08-31 16:56:12 -07001864
1865EventLoop *LogReader::State::SetNodeEventLoopFactory(
1866 NodeEventLoopFactory *node_event_loop_factory) {
1867 node_event_loop_factory_ = node_event_loop_factory;
1868 event_loop_unique_ptr_ =
1869 node_event_loop_factory_->MakeEventLoop("log_reader");
1870 return event_loop_unique_ptr_.get();
1871}
1872
1873void LogReader::State::SetChannelCount(size_t count) {
1874 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001875 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001876 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001877 channel_source_state_.resize(count);
1878 factory_channel_index_.resize(count);
1879 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001880}
1881
1882void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001883 size_t logged_channel_index, size_t factory_channel_index,
1884 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001885 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001886 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001887 channels_[logged_channel_index] = std::move(sender);
1888 filters_[logged_channel_index] = filter;
1889 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1890
1891 if (source_state) {
1892 channel_source_state_[logged_channel_index] = source_state;
1893
1894 if (remote_timestamp_sender != nullptr) {
1895 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001896 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001897 }
1898 }
1899
1900 factory_channel_index_[logged_channel_index] = factory_channel_index;
1901}
1902
Austin Schuh287d43d2020-12-04 20:19:33 -08001903bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1904 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001905 uint32_t remote_queue_index = 0xffffffff;
1906
Austin Schuh287d43d2020-12-04 20:19:33 -08001907 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001908 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001909 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1910 ->queue_index_map_[timestamped_message.channel_index]
1911 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001912
Austin Schuh9942bae2021-01-07 22:06:44 -08001913 struct SentTimestamp {
1914 monotonic_clock::time_point monotonic_event_time;
1915 uint32_t queue_index;
1916 } search;
1917
Austin Schuh287d43d2020-12-04 20:19:33 -08001918 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001919 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001920
1921 // Find the sent time if available.
1922 auto element = std::lower_bound(
1923 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001924 [](ContiguousSentTimestamp a, SentTimestamp b) {
1925 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001926 return true;
1927 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001928 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001929 return false;
1930 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001931
1932 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001933 return true;
1934 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001935 if (a.starting_queue_index >= b.queue_index) {
1936 return false;
1937 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001938
Austin Schuh9942bae2021-01-07 22:06:44 -08001939 // If it isn't clearly below or above, it is below. Since we return
1940 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001941 return false;
1942 });
1943
1944 // TODO(austin): Be a bit more principled here, but we will want to do that
1945 // after the logger rewrite. We hit this when one node finishes, but the
1946 // other node isn't done yet. So there is no send time, but there is a
1947 // receive time.
1948 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001949 CHECK_GE(timestamped_message.monotonic_remote_time,
1950 element->starting_monotonic_event_time);
1951 CHECK_LE(timestamped_message.monotonic_remote_time,
1952 element->ending_monotonic_event_time);
1953 CHECK_GE(timestamped_message.remote_queue_index,
1954 element->starting_queue_index);
1955 CHECK_LE(timestamped_message.remote_queue_index,
1956 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001957
Austin Schuh9942bae2021-01-07 22:06:44 -08001958 remote_queue_index = timestamped_message.remote_queue_index +
1959 element->actual_queue_index -
1960 element->starting_queue_index;
1961 } else {
1962 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001963 }
1964 }
1965
1966 // Send! Use the replayed queue index here instead of the logged queue index
1967 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001968 const bool sent = sender->Send(
1969 timestamped_message.data.message().data()->Data(),
1970 timestamped_message.data.message().data()->size(),
1971 timestamped_message.monotonic_remote_time,
1972 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001973 if (!sent) return false;
1974
Austin Schuh287d43d2020-12-04 20:19:33 -08001975 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001976 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1977 // Nothing here, start a range with 0 length.
1978 ContiguousSentTimestamp timestamp;
1979 timestamp.starting_monotonic_event_time =
1980 timestamp.ending_monotonic_event_time =
1981 timestamped_message.monotonic_event_time;
1982 timestamp.starting_queue_index = timestamp.ending_queue_index =
1983 timestamped_message.queue_index;
1984 timestamp.actual_queue_index = sender->sent_queue_index();
1985 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1986 timestamp);
1987 } else {
1988 // We've got something. See if the next timestamp is still contiguous. If
1989 // so, grow it.
1990 ContiguousSentTimestamp *back =
1991 &queue_index_map_[timestamped_message.channel_index]->back();
1992 if ((back->starting_queue_index - back->actual_queue_index) ==
1993 (timestamped_message.queue_index - sender->sent_queue_index())) {
1994 back->ending_queue_index = timestamped_message.queue_index;
1995 back->ending_monotonic_event_time =
1996 timestamped_message.monotonic_event_time;
1997 } else {
1998 // Otherwise, make a new one.
1999 ContiguousSentTimestamp timestamp;
2000 timestamp.starting_monotonic_event_time =
2001 timestamp.ending_monotonic_event_time =
2002 timestamped_message.monotonic_event_time;
2003 timestamp.starting_queue_index = timestamp.ending_queue_index =
2004 timestamped_message.queue_index;
2005 timestamp.actual_queue_index = sender->sent_queue_index();
2006 queue_index_map_[timestamped_message.channel_index]->emplace_back(
2007 timestamp);
2008 }
2009 }
2010
2011 // TODO(austin): Should we prune the map? On a many day log, I only saw the
2012 // queue index diverge a couple of elements, which would be a very small
2013 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08002014 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
2015 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08002016 flatbuffers::FlatBufferBuilder fbb;
2017 fbb.ForceDefaults(true);
Austin Schuh315b96b2020-12-11 21:21:12 -08002018 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
Austin Schuh969cd602021-01-03 00:09:45 -08002019 fbb.CreateString(event_loop_->boot_uuid().string_view());
Austin Schuh315b96b2020-12-11 21:21:12 -08002020
Austin Schuh969cd602021-01-03 00:09:45 -08002021 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002022
2023 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002024 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002025
2026 // Swap the remote and sent metrics. They are from the sender's
2027 // perspective, not the receiver's perspective.
2028 message_header_builder.add_monotonic_sent_time(
2029 sender->monotonic_sent_time().time_since_epoch().count());
2030 message_header_builder.add_realtime_sent_time(
2031 sender->realtime_sent_time().time_since_epoch().count());
2032 message_header_builder.add_queue_index(sender->sent_queue_index());
2033
2034 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002035 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002036 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002037 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002038
2039 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002040 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002041
Austin Schuh969cd602021-01-03 00:09:45 -08002042 fbb.Finish(message_header_builder.Finish());
2043
2044 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2045 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
2046 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002047 }
2048
2049 return true;
2050}
2051
Austin Schuh969cd602021-01-03 00:09:45 -08002052LogReader::RemoteMessageSender::RemoteMessageSender(
2053 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2054 : event_loop_(event_loop),
2055 sender_(std::move(sender)),
2056 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2057
2058void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2059 if (remote_timestamps_.empty()) {
2060 CHECK_NOTNULL(timer_);
2061 timer_->Disable();
2062 scheduled_time_ = monotonic_clock::min_time;
2063 return;
2064 }
2065
2066 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2067 CHECK_NOTNULL(timer_);
2068 timer_->Setup(
2069 remote_timestamps_.front().monotonic_timestamp_time);
2070 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
2071 }
2072}
2073
2074void LogReader::RemoteMessageSender::Send(
2075 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
2076 monotonic_clock::time_point monotonic_timestamp_time) {
2077 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
2078 // resend the timestamp at the correct time, or we don't and can send it
2079 // immediately.
2080 if (monotonic_timestamp_time == monotonic_clock::min_time) {
2081 CHECK(remote_timestamps_.empty())
2082 << ": Unsupported mix of timestamps and no timestamps.";
2083 sender_.Send(std::move(remote_message));
2084 } else {
2085 remote_timestamps_.emplace_back(std::move(remote_message),
2086 monotonic_timestamp_time);
2087 ScheduleTimestamp();
2088 }
2089}
2090
2091void LogReader::RemoteMessageSender::SendTimestamp() {
2092 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_);
2093 CHECK(!remote_timestamps_.empty());
2094
2095 // Send out all timestamps at the currently scheduled time.
2096 while (remote_timestamps_.front().monotonic_timestamp_time ==
2097 scheduled_time_) {
2098 sender_.Send(std::move(remote_timestamps_.front().remote_message));
2099 remote_timestamps_.pop_front();
2100 if (remote_timestamps_.empty()) {
2101 break;
2102 }
2103 }
2104 scheduled_time_ = monotonic_clock::min_time;
2105
2106 ScheduleTimestamp();
2107}
2108
2109LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002110 const Node *delivered_node) {
2111 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2112
2113 if (sender == remote_timestamp_senders_map_.end()) {
Austin Schuh969cd602021-01-03 00:09:45 -08002114 sender =
2115 remote_timestamp_senders_map_
2116 .emplace(delivered_node,
2117 std::make_unique<RemoteMessageSender>(
2118 event_loop()->MakeSender<RemoteMessage>(absl::StrCat(
2119 "/aos/remote_timestamps/",
2120 delivered_node->name()->string_view())),
2121 event_loop()))
2122 .first;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002123 }
2124
Austin Schuh969cd602021-01-03 00:09:45 -08002125 return sender->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002126}
2127
Austin Schuh188eabe2020-12-29 23:41:13 -08002128const TimestampedMessage &LogReader::State::PeekOldest() {
2129 return std::get<0>(sorted_messages_.front());
2130}
2131
Austin Schuh287d43d2020-12-04 20:19:33 -08002132TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002133 CHECK_GT(sorted_messages_.size(), 0u);
2134
Austin Schuh287d43d2020-12-04 20:19:33 -08002135 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002136 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002137 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002138 << std::get<0>(result).monotonic_event_time;
2139 sorted_messages_.pop_front();
2140 SeedSortedMessages();
2141
Austin Schuh287d43d2020-12-04 20:19:33 -08002142 if (std::get<1>(result) != nullptr) {
2143 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002144 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2145 } else {
2146 *update_time = false;
2147 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002148 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002149}
2150
2151monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2152 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002153 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002154 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2155 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2156 }
2157
Austin Schuh287d43d2020-12-04 20:19:33 -08002158 TimestampedMessage *m =
2159 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2160 if (m == nullptr) {
2161 return monotonic_clock::max_time;
2162 }
2163 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002164}
2165
2166void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002167 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002168 const aos::monotonic_clock::time_point end_queue_time =
2169 (sorted_messages_.size() > 0
2170 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002171 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002172 chrono::duration_cast<chrono::seconds>(
2173 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002174
2175 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002176 TimestampedMessage *m = timestamp_mapper_->Front();
2177 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002178 return;
2179 }
2180 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002181 // Stop placing sorted messages on the list once we have
2182 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2183 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002184 if (end_queue_time <
2185 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2186 return;
2187 }
2188 }
2189
Austin Schuh2f8fd752020-09-01 22:38:28 -07002190 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2191
Austin Schuh287d43d2020-12-04 20:19:33 -08002192 TimestampedMessage timestamped_message = std::move(*m);
2193 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002194
Austin Schuh2f8fd752020-09-01 22:38:28 -07002195 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002196 if (timestamped_message.monotonic_remote_time !=
2197 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002198 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002199 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002200
2201 CHECK(filter != nullptr);
2202
2203 // Call the correct method depending on if we are the forward or
2204 // reverse direction here.
2205 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002206 timestamped_message.monotonic_event_time,
2207 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002208 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002209 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002210 }
2211}
2212
2213void LogReader::State::Deregister() {
2214 for (size_t i = 0; i < channels_.size(); ++i) {
2215 channels_[i].reset();
2216 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002217 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002218 event_loop_unique_ptr_.reset();
2219 event_loop_ = nullptr;
2220 timer_handler_ = nullptr;
2221 node_event_loop_factory_ = nullptr;
2222}
2223
Austin Schuhe309d2a2019-11-29 13:25:21 -08002224} // namespace logger
2225} // namespace aos