blob: fbea0924c5eb849cab02fa093f3ecfa594c69318 [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
Austin Schuh4c4e0092019-12-22 16:18:03 -08004#include <limits.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
8#include <vector>
9
Austin Schuh8bd96322020-02-13 21:18:22 -080010#include "Eigen/Dense"
Austin Schuh2f8fd752020-09-01 22:38:28 -070011#include "absl/strings/escaping.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080012#include "absl/types/span.h"
13#include "aos/events/event_loop.h"
Austin Schuhf6f9bf32020-10-11 14:37:43 -070014#include "aos/events/logging/logfile_sorting.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080015#include "aos/events/logging/logger_generated.h"
Austin Schuh64fab802020-09-09 22:47:47 -070016#include "aos/events/logging/uuid.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080017#include "aos/flatbuffer_merge.h"
Austin Schuh0ca1fd32020-12-18 22:53:05 -080018#include "aos/network/multinode_timestamp_filter.h"
Austin Schuh0de30f32020-12-06 12:44:28 -080019#include "aos/network/remote_message_generated.h"
20#include "aos/network/remote_message_schema.h"
Austin Schuh288479d2019-12-18 19:47:52 -080021#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080022#include "aos/time/time.h"
Brian Silvermanae7c0332020-09-30 16:58:23 -070023#include "aos/util/file.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080024#include "flatbuffers/flatbuffers.h"
Austin Schuh8c399962020-12-25 21:51:45 -080025#include "openssl/sha.h"
Austin Schuh2f8fd752020-09-01 22:38:28 -070026#include "third_party/gmp/gmpxx.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080027
Austin Schuh15649d62019-12-28 16:36:38 -080028DEFINE_bool(skip_missing_forwarding_entries, false,
29 "If true, drop any forwarding entries with missing data. If "
30 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080031
Austin Schuh0ca1fd32020-12-18 22:53:05 -080032DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080033
Austin Schuh2f8fd752020-09-01 22:38:28 -070034DEFINE_bool(skip_order_validation, false,
35 "If true, ignore any out of orderness in replay");
36
Austin Schuhf0688662020-12-19 15:37:45 -080037DEFINE_double(
38 time_estimation_buffer_seconds, 2.0,
39 "The time to buffer ahead in the log file to accurately reconstruct time.");
40
Austin Schuhe309d2a2019-11-29 13:25:21 -080041namespace aos {
42namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070043namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080044std::string Sha256(const absl::Span<const uint8_t> str) {
45 unsigned char hash[SHA256_DIGEST_LENGTH];
46 SHA256_CTX sha256;
47 SHA256_Init(&sha256);
48 SHA256_Update(&sha256, str.data(), str.size());
49 SHA256_Final(hash, &sha256);
50 std::stringstream ss;
51 for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) {
52 ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
53 }
54 return ss.str();
55}
56
Austin Schuh315b96b2020-12-11 21:21:12 -080057std::string LogFileVectorToString(std::vector<LogFile> log_files) {
58 std::stringstream ss;
59 for (const auto f : log_files) {
60 ss << f << "\n";
61 }
62 return ss.str();
63}
64
Austin Schuh0de30f32020-12-06 12:44:28 -080065// Copies the channel, removing the schema as we go. If new_name is provided,
66// it is used instead of the name inside the channel. If new_type is provided,
67// it is used instead of the type in the channel.
68flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
69 std::string_view new_name,
70 std::string_view new_type,
71 flatbuffers::FlatBufferBuilder *fbb) {
72 flatbuffers::Offset<flatbuffers::String> name_offset =
73 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
74 : new_name);
75 flatbuffers::Offset<flatbuffers::String> type_offset =
76 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
77 flatbuffers::Offset<flatbuffers::String> source_node_offset =
78 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
79 : 0;
80
81 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
82 destination_nodes_offset =
83 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
84
85 flatbuffers::Offset<
86 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
87 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
88
89 Channel::Builder channel_builder(*fbb);
90 channel_builder.add_name(name_offset);
91 channel_builder.add_type(type_offset);
92 if (c->has_frequency()) {
93 channel_builder.add_frequency(c->frequency());
94 }
95 if (c->has_max_size()) {
96 channel_builder.add_max_size(c->max_size());
97 }
98 if (c->has_num_senders()) {
99 channel_builder.add_num_senders(c->num_senders());
100 }
101 if (c->has_num_watchers()) {
102 channel_builder.add_num_watchers(c->num_watchers());
103 }
104 if (!source_node_offset.IsNull()) {
105 channel_builder.add_source_node(source_node_offset);
106 }
107 if (!destination_nodes_offset.IsNull()) {
108 channel_builder.add_destination_nodes(destination_nodes_offset);
109 }
110 if (c->has_logger()) {
111 channel_builder.add_logger(c->logger());
112 }
113 if (!logger_nodes_offset.IsNull()) {
114 channel_builder.add_logger_nodes(logger_nodes_offset);
115 }
116 if (c->has_read_method()) {
117 channel_builder.add_read_method(c->read_method());
118 }
119 if (c->has_num_readers()) {
120 channel_builder.add_num_readers(c->num_readers());
121 }
122 return channel_builder.Finish();
123}
124
Austin Schuhe309d2a2019-11-29 13:25:21 -0800125namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800126using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700127} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800128
Brian Silverman1f345222020-09-24 21:14:48 -0700129Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
130 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800131 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700132 configuration_(configuration),
133 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700134 timer_handler_(event_loop_->AddTimer(
135 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700136 server_statistics_fetcher_(
137 configuration::MultiNode(event_loop_->configuration())
138 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
139 "/aos")
140 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700141 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700142
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700143 // Find all the nodes which are logging timestamps on our node. This may
144 // over-estimate if should_log is specified.
145 std::vector<const Node *> timestamp_logger_nodes =
146 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700147
148 std::map<const Channel *, const Node *> timestamp_logger_channels;
149
150 // Now that we have all the nodes accumulated, make remote timestamp loggers
151 // for them.
152 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700153 // Note: since we are doing a find using the event loop channel, we need to
154 // make sure this channel pointer is part of the event loop configuration,
155 // not configuration_. This only matters when configuration_ !=
156 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700157 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700158 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700159 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800160 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700161 event_loop_->node());
162
163 CHECK(channel != nullptr)
164 << ": Remote timestamps are logged on "
165 << event_loop_->node()->name()->string_view()
166 << " but can't find channel /aos/remote_timestamps/"
167 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700168 if (!should_log(channel)) {
169 continue;
170 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700171 timestamp_logger_channels.insert(std::make_pair(channel, node));
172 }
173
Brian Silvermand90905f2020-09-23 14:42:56 -0700174 const size_t our_node_index =
175 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700176
Brian Silverman1f345222020-09-24 21:14:48 -0700177 for (size_t channel_index = 0;
178 channel_index < configuration_->channels()->size(); ++channel_index) {
179 const Channel *const config_channel =
180 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700181 // The MakeRawFetcher method needs a channel which is in the event loop
182 // configuration() object, not the configuration_ object. Go look that up
183 // from the config.
184 const Channel *channel = aos::configuration::GetChannel(
185 event_loop_->configuration(), config_channel->name()->string_view(),
186 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700187 CHECK(channel != nullptr)
188 << ": Failed to look up channel "
189 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700190 if (!should_log(channel)) {
191 continue;
192 }
Austin Schuh0c297012020-09-16 18:41:59 -0700193
Austin Schuhe309d2a2019-11-29 13:25:21 -0800194 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700195 fs.channel_index = channel_index;
196 fs.channel = channel;
197
Austin Schuh6f3babe2020-01-26 20:34:50 -0800198 const bool is_local =
199 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
200
Austin Schuh15649d62019-12-28 16:36:38 -0800201 const bool is_readable =
202 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700203 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
204 channel, event_loop_->node());
205 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800206
Brian Silverman1f345222020-09-24 21:14:48 -0700207 bool log_delivery_times = false;
208 if (event_loop_->node() != nullptr) {
209 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
210 channel, event_loop_->node(), event_loop_->node());
211 }
Austin Schuh15649d62019-12-28 16:36:38 -0800212
Austin Schuh0de30f32020-12-06 12:44:28 -0800213 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700214 // contents to a file directly.
215 const bool log_contents = timestamp_logger_channels.find(channel) !=
216 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700217
218 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800219 fs.fetcher = event_loop->MakeRawFetcher(channel);
220 VLOG(1) << "Logging channel "
221 << configuration::CleanedChannelToString(channel);
222
223 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700225 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800226 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800227 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800228 if (log_message) {
229 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700230 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800231 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800232 const Node *source_node = configuration::GetNode(
233 configuration_, channel->source_node()->string_view());
234 fs.data_node_index =
235 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800237 } else {
238 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800239 }
240 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700241 if (log_contents) {
242 VLOG(1) << "Timestamp logger channel "
243 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700244 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
245 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800246 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700247 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700248 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800249 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800250 }
Brian Silverman1f345222020-09-24 21:14:48 -0700251 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700252
253 // When we are logging remote timestamps, we need to be able to translate from
254 // the channel index that the event loop uses to the channel index in the
255 // config in the log file.
256 event_loop_to_logged_channel_index_.resize(
257 event_loop->configuration()->channels()->size(), -1);
258 for (size_t event_loop_channel_index = 0;
259 event_loop_channel_index <
260 event_loop->configuration()->channels()->size();
261 ++event_loop_channel_index) {
262 const Channel *event_loop_channel =
263 event_loop->configuration()->channels()->Get(event_loop_channel_index);
264
265 const Channel *logged_channel = aos::configuration::GetChannel(
266 configuration_, event_loop_channel->name()->string_view(),
267 event_loop_channel->type()->string_view(), "",
268 configuration::GetNode(configuration_, event_loop_->node()));
269
270 if (logged_channel != nullptr) {
271 event_loop_to_logged_channel_index_[event_loop_channel_index] =
272 configuration::ChannelIndex(configuration_, logged_channel);
273 }
274 }
Brian Silverman1f345222020-09-24 21:14:48 -0700275}
276
277Logger::~Logger() {
278 if (log_namer_) {
279 // If we are replaying a log file, or in simulation, we want to force the
280 // last bit of data to be logged. The easiest way to deal with this is to
281 // poll everything as we go to destroy the class, ie, shut down the logger,
282 // and write it to disk.
283 StopLogging(event_loop_->monotonic_now());
284 }
285}
286
Brian Silvermanae7c0332020-09-30 16:58:23 -0700287void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
288 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700289 CHECK(!log_namer_) << ": Already logging";
290 log_namer_ = std::move(log_namer);
Austin Schuh8c399962020-12-25 21:51:45 -0800291
292 std::string config_sha256;
293 if (separate_config_) {
294 flatbuffers::FlatBufferBuilder fbb;
295 flatbuffers::Offset<aos::Configuration> configuration_offset =
296 CopyFlatBuffer(configuration_, &fbb);
297 LogFileHeader::Builder log_file_header_builder(fbb);
298 log_file_header_builder.add_configuration(configuration_offset);
299 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
300 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> config_header(
301 fbb.Release());
302 config_sha256 = Sha256(config_header.span());
303 LOG(INFO) << "Config sha256 of " << config_sha256;
304 log_namer_->WriteConfiguration(&config_header, config_sha256);
305 }
306
Brian Silvermanae7c0332020-09-30 16:58:23 -0700307 log_event_uuid_ = UUID::Random();
308 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700309 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
310
311 // We want to do as much work as possible before the initial Fetch. Time
312 // between that and actually starting to log opens up the possibility of
313 // falling off the end of the queue during that time.
314
315 for (FetcherStruct &f : fetchers_) {
316 if (f.wants_writer) {
317 f.writer = log_namer_->MakeWriter(f.channel);
318 }
319 if (f.wants_timestamp_writer) {
320 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
321 }
322 if (f.wants_contents_writer) {
323 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
324 f.channel, CHECK_NOTNULL(f.timestamp_node));
325 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800326 }
327
Brian Silverman1f345222020-09-24 21:14:48 -0700328 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700329 node_state_.resize(configuration::MultiNode(configuration_)
330 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700331 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800332
Austin Schuh2f8fd752020-09-01 22:38:28 -0700333 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700334 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800335
Austin Schuh8c399962020-12-25 21:51:45 -0800336 node_state_[node_index].log_file_header =
337 MakeHeader(node, config_sha256);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700338 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800339
Austin Schuh2f8fd752020-09-01 22:38:28 -0700340 // Grab data from each channel right before we declare the log file started
341 // so we can capture the latest message on each channel. This lets us have
342 // non periodic messages with configuration that now get logged.
343 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700344 const auto start = event_loop_->monotonic_now();
345 const bool got_new = f.fetcher->Fetch();
346 const auto end = event_loop_->monotonic_now();
347 RecordFetchResult(start, end, got_new, &f);
348
349 // If there is a message, we want to write it.
350 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700351 }
352
353 // Clear out any old timestamps in case we are re-starting logging.
354 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800355 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
356 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700357 }
358
359 WriteHeader();
360
361 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
362 << " start_time " << last_synchronized_time_;
363
Austin Schuh315b96b2020-12-11 21:21:12 -0800364 // Force logging up until the start of the log file now, so the messages at
365 // the start are always ordered before the rest of the messages.
366 // Note: this ship may have already sailed, but we don't have to make it
367 // worse.
368 // TODO(austin): Test...
369 LogUntil(last_synchronized_time_);
370
Austin Schuh2f8fd752020-09-01 22:38:28 -0700371 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
372 polling_period_);
373}
374
Brian Silverman1f345222020-09-24 21:14:48 -0700375std::unique_ptr<LogNamer> Logger::StopLogging(
376 aos::monotonic_clock::time_point end_time) {
377 CHECK(log_namer_) << ": Not logging right now";
378
379 if (end_time != aos::monotonic_clock::min_time) {
380 LogUntil(end_time);
381 }
382 timer_handler_->Disable();
383
384 for (FetcherStruct &f : fetchers_) {
385 f.writer = nullptr;
386 f.timestamp_writer = nullptr;
387 f.contents_writer = nullptr;
388 }
389 node_state_.clear();
390
Brian Silvermanae7c0332020-09-30 16:58:23 -0700391 log_event_uuid_ = UUID::Zero();
392 log_start_uuid_ = std::string();
393
Brian Silverman1f345222020-09-24 21:14:48 -0700394 return std::move(log_namer_);
395}
396
Austin Schuhfa895892020-01-07 20:07:41 -0800397void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700398 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700399 server_statistics_fetcher_.Fetch();
400 }
401
402 aos::monotonic_clock::time_point monotonic_start_time =
403 event_loop_->monotonic_now();
404 aos::realtime_clock::time_point realtime_start_time =
405 event_loop_->realtime_now();
406
407 // We need to pick a point in time to declare the log file "started". This
408 // starts here. It needs to be after everything is fetched so that the
409 // fetchers are all pointed at the most recent message before the start
410 // time.
411 last_synchronized_time_ = monotonic_start_time;
412
Austin Schuh6f3babe2020-01-26 20:34:50 -0800413 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700414 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700415 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
416 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800417 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800418 }
419}
Austin Schuh8bd96322020-02-13 21:18:22 -0800420
Austin Schuh315b96b2020-12-11 21:21:12 -0800421void Logger::MaybeWriteHeader(int node_index) {
422 if (configuration::MultiNode(configuration_)) {
423 return MaybeWriteHeader(node_index,
424 configuration_->nodes()->Get(node_index));
425 } else {
426 return MaybeWriteHeader(node_index, nullptr);
427 }
428}
429
430void Logger::MaybeWriteHeader(int node_index, const Node *node) {
431 // This function is responsible for writing the header when the header both
432 // has valid data, and when it needs to be written.
433 if (node_state_[node_index].header_written &&
434 node_state_[node_index].header_valid) {
435 // The header has been written and is valid, nothing to do.
436 return;
437 }
438 if (!node_state_[node_index].has_source_node_boot_uuid) {
439 // Can't write a header if we don't have the boot UUID.
440 return;
441 }
442
443 // WriteHeader writes the first header in a log file. We want to do this only
444 // once.
445 //
446 // Rotate rewrites the same header with a new part ID, but keeps the same part
447 // UUID. We don't want that when things reboot, because that implies that
448 // parts go together across a reboot.
449 //
450 // Reboot resets the parts UUID. So, once we've written a header the first
451 // time, we want to use Reboot to rotate the log and reset the parts UUID.
452 //
453 // header_valid is cleared whenever the remote reboots.
454 if (node_state_[node_index].header_written) {
455 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
456 } else {
457 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
458
459 node_state_[node_index].header_written = true;
460 }
461 node_state_[node_index].header_valid = true;
462}
463
Austin Schuh2f8fd752020-09-01 22:38:28 -0700464void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700465 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700466 server_statistics_fetcher_.Fetch();
467 } else {
468 return;
469 }
470
471 if (server_statistics_fetcher_.get() == nullptr) {
472 return;
473 }
474
475 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700476 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700477 if (MaybeUpdateTimestamp(
478 node, node_index,
479 server_statistics_fetcher_.context().monotonic_event_time,
480 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800481 CHECK(node_state_[node_index].header_written);
482 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700483 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800484 } else {
485 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700486 }
487 }
488}
489
Austin Schuh315b96b2020-12-11 21:21:12 -0800490void Logger::SetStartTime(
491 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
492 aos::realtime_clock::time_point realtime_start_time,
493 aos::monotonic_clock::time_point logger_monotonic_start_time,
494 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700495 node_state_[node_index].monotonic_start_time = monotonic_start_time;
496 node_state_[node_index].realtime_start_time = realtime_start_time;
497 node_state_[node_index]
498 .log_file_header.mutable_message()
499 ->mutate_monotonic_start_time(
500 std::chrono::duration_cast<std::chrono::nanoseconds>(
501 monotonic_start_time.time_since_epoch())
502 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800503
504 // Add logger start times if they are available in the log file header.
505 if (node_state_[node_index]
506 .log_file_header.mutable_message()
507 ->has_logger_monotonic_start_time()) {
508 node_state_[node_index]
509 .log_file_header.mutable_message()
510 ->mutate_logger_monotonic_start_time(
511 std::chrono::duration_cast<std::chrono::nanoseconds>(
512 logger_monotonic_start_time.time_since_epoch())
513 .count());
514 }
515
516 if (node_state_[node_index]
517 .log_file_header.mutable_message()
518 ->has_logger_realtime_start_time()) {
519 node_state_[node_index]
520 .log_file_header.mutable_message()
521 ->mutate_logger_realtime_start_time(
522 std::chrono::duration_cast<std::chrono::nanoseconds>(
523 logger_realtime_start_time.time_since_epoch())
524 .count());
525 }
526
Austin Schuh2f8fd752020-09-01 22:38:28 -0700527 if (node_state_[node_index]
528 .log_file_header.mutable_message()
529 ->has_realtime_start_time()) {
530 node_state_[node_index]
531 .log_file_header.mutable_message()
532 ->mutate_realtime_start_time(
533 std::chrono::duration_cast<std::chrono::nanoseconds>(
534 realtime_start_time.time_since_epoch())
535 .count());
536 }
537}
538
539bool Logger::MaybeUpdateTimestamp(
540 const Node *node, int node_index,
541 aos::monotonic_clock::time_point monotonic_start_time,
542 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700543 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700544 if (node_state_[node_index].monotonic_start_time !=
545 monotonic_clock::min_time) {
546 return false;
547 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800548 if (event_loop_->node() == node ||
549 !configuration::MultiNode(configuration_)) {
550 // There are no offsets to compute for ourself, so always succeed.
551 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
552 monotonic_start_time, realtime_start_time);
553 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700554 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800555 } else if (server_statistics_fetcher_.get() != nullptr) {
556 // We must be a remote node now. Look for the connection and see if it is
557 // connected.
558
559 for (const message_bridge::ServerConnection *connection :
560 *server_statistics_fetcher_->connections()) {
561 if (connection->node()->name()->string_view() !=
562 node->name()->string_view()) {
563 continue;
564 }
565
566 if (connection->state() != message_bridge::State::CONNECTED) {
567 VLOG(1) << node->name()->string_view()
568 << " is not connected, can't start it yet.";
569 break;
570 }
571
572 // Update the boot UUID as soon as we know we are connected.
573 if (!connection->has_boot_uuid()) {
574 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
575 break;
576 }
577
578 if (!node_state_[node_index].has_source_node_boot_uuid ||
579 node_state_[node_index].source_node_boot_uuid !=
580 connection->boot_uuid()->string_view()) {
581 node_state_[node_index].SetBootUUID(
582 connection->boot_uuid()->string_view());
583 }
584
585 if (!connection->has_monotonic_offset()) {
586 VLOG(1) << "Missing monotonic offset for setting start time for node "
587 << aos::FlatbufferToJson(node);
588 break;
589 }
590
591 // Found it and it is connected. Compensate and go.
592 SetStartTime(node_index,
593 monotonic_start_time +
594 std::chrono::nanoseconds(connection->monotonic_offset()),
595 realtime_start_time, monotonic_start_time,
596 realtime_start_time);
597 return true;
598 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700599 }
600 return false;
601}
602
603aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
Austin Schuh8c399962020-12-25 21:51:45 -0800604 const Node *node, std::string_view config_sha256) {
Austin Schuhfa895892020-01-07 20:07:41 -0800605 // Now write the header with this timestamp in it.
606 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800607 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800608
Austin Schuh8c399962020-12-25 21:51:45 -0800609 flatbuffers::Offset<aos::Configuration> configuration_offset;
610 if (!separate_config_) {
611 configuration_offset = CopyFlatBuffer(configuration_, &fbb);
612 } else {
613 CHECK(!config_sha256.empty());
614 }
Austin Schuhfa895892020-01-07 20:07:41 -0800615
Brian Silvermanae7c0332020-09-30 16:58:23 -0700616 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700617 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800618
Brian Silvermanae7c0332020-09-30 16:58:23 -0700619 CHECK(log_event_uuid_ != UUID::Zero());
620 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
621 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700622
Brian Silvermanae7c0332020-09-30 16:58:23 -0700623 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
624 fbb.CreateString(logger_instance_uuid_.string_view());
625
626 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
627 if (!log_start_uuid_.empty()) {
628 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
629 }
630
Austin Schuh8c399962020-12-25 21:51:45 -0800631 flatbuffers::Offset<flatbuffers::String> config_sha256_offset;
632 if (!config_sha256.empty()) {
633 config_sha256_offset = fbb.CreateString(config_sha256);
634 }
635
Austin Schuh315b96b2020-12-11 21:21:12 -0800636 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
637 fbb.CreateString(event_loop_->boot_uuid().string_view());
638
639 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
640 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700641
642 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700643 fbb.CreateString("00000000-0000-4000-8000-000000000000");
644
Austin Schuhfa895892020-01-07 20:07:41 -0800645 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700646 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700647
Austin Schuh0c297012020-09-16 18:41:59 -0700648 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800649 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
650 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800651 }
652
653 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
654
Austin Schuh64fab802020-09-09 22:47:47 -0700655 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800656
657 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800658 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800659 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700660 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800661 }
662
Austin Schuh8c399962020-12-25 21:51:45 -0800663 if (!configuration_offset.IsNull()) {
664 log_file_header_builder.add_configuration(configuration_offset);
665 }
Austin Schuhfa895892020-01-07 20:07:41 -0800666 // The worst case theoretical out of order is the polling period times 2.
667 // One message could get logged right after the boundary, but be for right
668 // before the next boundary. And the reverse could happen for another
669 // message. Report back 3x to be extra safe, and because the cost isn't
670 // huge on the read side.
671 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700672 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800673
674 log_file_header_builder.add_monotonic_start_time(
675 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700676 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800677 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700678 if (node == event_loop_->node()) {
679 log_file_header_builder.add_realtime_start_time(
680 std::chrono::duration_cast<std::chrono::nanoseconds>(
681 realtime_clock::min_time.time_since_epoch())
682 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800683 } else {
684 log_file_header_builder.add_logger_monotonic_start_time(
685 std::chrono::duration_cast<std::chrono::nanoseconds>(
686 monotonic_clock::min_time.time_since_epoch())
687 .count());
688 log_file_header_builder.add_logger_realtime_start_time(
689 std::chrono::duration_cast<std::chrono::nanoseconds>(
690 realtime_clock::min_time.time_since_epoch())
691 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800692 }
693
Brian Silvermanae7c0332020-09-30 16:58:23 -0700694 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
695 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
696 if (!log_start_uuid_offset.IsNull()) {
697 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
698 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800699 log_file_header_builder.add_logger_node_boot_uuid(
700 logger_node_boot_uuid_offset);
701 log_file_header_builder.add_source_node_boot_uuid(
702 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700703
704 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
705 log_file_header_builder.add_parts_index(0);
706
Austin Schuh8c399962020-12-25 21:51:45 -0800707 log_file_header_builder.add_configuration_sha256(0);
708
709 if (!config_sha256_offset.IsNull()) {
710 log_file_header_builder.add_configuration_sha256(config_sha256_offset);
711 }
712
Austin Schuh2f8fd752020-09-01 22:38:28 -0700713 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800714 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
715 fbb.Release());
716
717 CHECK(result.Verify()) << ": Built a corrupted header.";
718
719 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700720}
721
Brian Silvermancb805822020-10-06 17:43:35 -0700722void Logger::ResetStatisics() {
723 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
724 max_message_fetch_time_channel_ = -1;
725 max_message_fetch_time_size_ = -1;
726 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
727 total_message_fetch_count_ = 0;
728 total_message_fetch_bytes_ = 0;
729 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
730 total_nop_fetch_count_ = 0;
731 max_copy_time_ = std::chrono::nanoseconds::zero();
732 max_copy_time_channel_ = -1;
733 max_copy_time_size_ = -1;
734 total_copy_time_ = std::chrono::nanoseconds::zero();
735 total_copy_count_ = 0;
736 total_copy_bytes_ = 0;
737}
738
Austin Schuh2f8fd752020-09-01 22:38:28 -0700739void Logger::Rotate() {
740 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700741 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700742 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700743 }
744}
745
746void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800747 // Grab the latest ServerStatistics message. This will always have the
748 // oppertunity to be >= to the current time, so it will always represent any
749 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700750 WriteMissingTimestamps();
751
752 // Write each channel to disk, one at a time.
753 for (FetcherStruct &f : fetchers_) {
754 while (true) {
755 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700756 const auto start = event_loop_->monotonic_now();
757 const bool got_new = f.fetcher->FetchNext();
758 const auto end = event_loop_->monotonic_now();
759 RecordFetchResult(start, end, got_new, &f);
760 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700761 VLOG(2) << "No new data on "
762 << configuration::CleanedChannelToString(
763 f.fetcher->channel());
764 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700765 }
Brian Silvermancb805822020-10-06 17:43:35 -0700766 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700767 }
768
Austin Schuh2f8fd752020-09-01 22:38:28 -0700769 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700770 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700771 break;
772 }
Brian Silvermancb805822020-10-06 17:43:35 -0700773 if (f.writer != nullptr) {
774 // Write!
775 const auto start = event_loop_->monotonic_now();
776 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
777 max_header_size_);
778 fbb.ForceDefaults(true);
779
780 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
781 f.channel_index, f.log_type));
782 const auto end = event_loop_->monotonic_now();
783 RecordCreateMessageTime(start, end, &f);
784
785 VLOG(2) << "Writing data as node "
786 << FlatbufferToJson(event_loop_->node()) << " for channel "
787 << configuration::CleanedChannelToString(f.fetcher->channel())
788 << " to " << f.writer->filename() << " data "
789 << FlatbufferToJson(
790 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
791 fbb.GetBufferPointer()));
792
793 max_header_size_ = std::max(max_header_size_,
794 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800795 CHECK(node_state_[f.data_node_index].header_valid)
796 << ": Can't write data before the header on channel "
797 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700798 f.writer->QueueSizedFlatbuffer(&fbb);
799 }
800
801 if (f.timestamp_writer != nullptr) {
802 // And now handle timestamps.
803 const auto start = event_loop_->monotonic_now();
804 flatbuffers::FlatBufferBuilder fbb;
805 fbb.ForceDefaults(true);
806
807 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
808 f.channel_index,
809 LogType::kLogDeliveryTimeOnly));
810 const auto end = event_loop_->monotonic_now();
811 RecordCreateMessageTime(start, end, &f);
812
813 VLOG(2) << "Writing timestamps as node "
814 << FlatbufferToJson(event_loop_->node()) << " for channel "
815 << configuration::CleanedChannelToString(f.fetcher->channel())
816 << " to " << f.timestamp_writer->filename() << " timestamp "
817 << FlatbufferToJson(
818 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
819 fbb.GetBufferPointer()));
820
Austin Schuh315b96b2020-12-11 21:21:12 -0800821 CHECK(node_state_[f.timestamp_node_index].header_valid)
822 << ": Can't write data before the header on channel "
823 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700824 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
825 }
826
827 if (f.contents_writer != nullptr) {
828 const auto start = event_loop_->monotonic_now();
829 // And now handle the special message contents channel. Copy the
830 // message into a FlatBufferBuilder and save it to disk.
831 // TODO(austin): We can be more efficient here when we start to
832 // care...
833 flatbuffers::FlatBufferBuilder fbb;
834 fbb.ForceDefaults(true);
835
Austin Schuh0de30f32020-12-06 12:44:28 -0800836 const RemoteMessage *msg =
837 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700838
Austin Schuh315b96b2020-12-11 21:21:12 -0800839 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
840 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
841 node_state_[f.contents_node_index].source_node_boot_uuid !=
842 msg->boot_uuid()->string_view()) {
843 node_state_[f.contents_node_index].SetBootUUID(
844 msg->boot_uuid()->string_view());
845
846 MaybeWriteHeader(f.contents_node_index);
847 }
848
Brian Silvermancb805822020-10-06 17:43:35 -0700849 logger::MessageHeader::Builder message_header_builder(fbb);
850
851 // TODO(austin): This needs to check the channel_index and confirm
852 // that it should be logged before squirreling away the timestamp to
853 // disk. We don't want to log irrelevant timestamps.
854
855 // Note: this must match the same order as MessageBridgeServer and
856 // PackMessage. We want identical headers to have identical
857 // on-the-wire formats to make comparing them easier.
858
859 // Translate from the channel index that the event loop uses to the
860 // channel index in the log file.
861 message_header_builder.add_channel_index(
862 event_loop_to_logged_channel_index_[msg->channel_index()]);
863
864 message_header_builder.add_queue_index(msg->queue_index());
865 message_header_builder.add_monotonic_sent_time(
866 msg->monotonic_sent_time());
867 message_header_builder.add_realtime_sent_time(
868 msg->realtime_sent_time());
869
870 message_header_builder.add_monotonic_remote_time(
871 msg->monotonic_remote_time());
872 message_header_builder.add_realtime_remote_time(
873 msg->realtime_remote_time());
874 message_header_builder.add_remote_queue_index(
875 msg->remote_queue_index());
876
Austin Schuh969cd602021-01-03 00:09:45 -0800877 message_header_builder.add_monotonic_timestamp_time(
878 f.fetcher->context()
879 .monotonic_event_time.time_since_epoch()
880 .count());
881
Brian Silvermancb805822020-10-06 17:43:35 -0700882 fbb.FinishSizePrefixed(message_header_builder.Finish());
883 const auto end = event_loop_->monotonic_now();
884 RecordCreateMessageTime(start, end, &f);
885
Austin Schuh315b96b2020-12-11 21:21:12 -0800886 CHECK(node_state_[f.contents_node_index].header_valid)
887 << ": Can't write data before the header on channel "
888 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700889 f.contents_writer->QueueSizedFlatbuffer(&fbb);
890 }
891
892 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700893 }
894 }
895 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800896}
897
Brian Silverman1f345222020-09-24 21:14:48 -0700898void Logger::DoLogData(const monotonic_clock::time_point end_time) {
899 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800900 // max_out_of_order_duration. To do this, we need sync points. Every write
901 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800902
903 do {
904 // Move the sync point up by at most polling_period. This forces one sync
905 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700906 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
907
908 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800909
Austin Schuhe309d2a2019-11-29 13:25:21 -0800910 // If we missed cycles, we could be pretty far behind. Spin until we are
911 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700912 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800913}
914
Brian Silvermancb805822020-10-06 17:43:35 -0700915void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
916 aos::monotonic_clock::time_point end,
917 bool got_new, FetcherStruct *fetcher) {
918 const auto duration = end - start;
919 if (!got_new) {
920 ++total_nop_fetch_count_;
921 total_nop_fetch_time_ += duration;
922 return;
923 }
924 ++total_message_fetch_count_;
925 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
926 total_message_fetch_time_ += duration;
927 if (duration > max_message_fetch_time_) {
928 max_message_fetch_time_ = duration;
929 max_message_fetch_time_channel_ = fetcher->channel_index;
930 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
931 }
932}
933
934void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
935 aos::monotonic_clock::time_point end,
936 FetcherStruct *fetcher) {
937 const auto duration = end - start;
938 total_copy_time_ += duration;
939 ++total_copy_count_;
940 total_copy_bytes_ += fetcher->fetcher->context().size;
941 if (duration > max_copy_time_) {
942 max_copy_time_ = duration;
943 max_copy_time_channel_ = fetcher->channel_index;
944 max_copy_time_size_ = fetcher->fetcher->context().size;
945 }
946}
947
Austin Schuh11d43732020-09-21 17:28:30 -0700948std::vector<std::vector<std::string>> ToLogReaderVector(
949 const std::vector<LogFile> &log_files) {
950 std::vector<std::vector<std::string>> result;
951 for (const LogFile &log_file : log_files) {
952 for (const LogParts &log_parts : log_file.parts) {
953 std::vector<std::string> parts;
954 for (const std::string &part : log_parts.parts) {
955 parts.emplace_back(part);
956 }
957 result.emplace_back(std::move(parts));
958 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700959 }
960 return result;
961}
962
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800963LogReader::LogReader(std::string_view filename,
964 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800965 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800966
Austin Schuh287d43d2020-12-04 20:19:33 -0800967LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800968 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800969 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800970 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800971 CHECK_GT(log_files_.size(), 0u);
972 {
973 // Validate that we have the same config everwhere. This will be true if
974 // all the parts were sorted together and the configs match.
975 const Configuration *config = nullptr;
976 for (const LogFile &log_file : log_files) {
977 if (config == nullptr) {
978 config = log_file.config.get();
979 } else {
980 CHECK_EQ(config, log_file.config.get());
981 }
982 }
983 }
Austin Schuh6331ef92020-01-07 18:28:09 -0800984 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800985
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700986 // Remap all existing remote timestamp channels. They will be recreated, and
987 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700988 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700989 std::vector<const Node *> timestamp_logger_nodes =
990 configuration::TimestampNodes(logged_configuration(), node);
991 for (const Node *remote_node : timestamp_logger_nodes) {
992 const std::string channel = absl::StrCat(
993 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800994 // See if the log file is an old log with MessageHeader channels in it, or
995 // a newer log with RemoteMessage. If we find an older log, rename the
996 // type too along with the name.
997 if (HasChannel<MessageHeader>(channel, node)) {
998 CHECK(!HasChannel<RemoteMessage>(channel, node))
999 << ": Can't have both a MessageHeader and RemoteMessage remote "
1000 "timestamp channel.";
1001 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
1002 "aos.message_bridge.RemoteMessage");
1003 } else {
1004 CHECK(HasChannel<RemoteMessage>(channel, node))
1005 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
1006 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
1007 << node->name()->string_view();
1008 RemapLoggedChannel<RemoteMessage>(channel, node);
1009 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001010 }
1011 }
1012
Austin Schuh6aa77be2020-02-22 21:06:40 -08001013 if (replay_configuration) {
1014 CHECK_EQ(configuration::MultiNode(configuration()),
1015 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001016 << ": Log file and replay config need to both be multi or single "
1017 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -08001018 }
1019
Austin Schuh6f3babe2020-01-26 20:34:50 -08001020 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001021 states_.emplace_back(std::make_unique<State>(
1022 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -08001023 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001024 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -07001025 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -08001026 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -07001027 << ": Log file and replay config need to have matching nodes "
1028 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001029 for (const Node *node : *logged_configuration()->nodes()) {
1030 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001031 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
1032 << " in logged config that is not present in the replay "
1033 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001034 }
1035 }
Austin Schuh6aa77be2020-02-22 21:06:40 -08001036 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001037 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001038 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001039}
1040
Austin Schuh6aa77be2020-02-22 21:06:40 -08001041LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -07001042 if (event_loop_factory_unique_ptr_) {
1043 Deregister();
1044 } else if (event_loop_factory_ != nullptr) {
1045 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
1046 "is destroyed";
1047 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001048 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1049 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001050 if (remapped_configuration_buffer_) {
1051 remapped_configuration_buffer_->Wipe();
1052 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001053}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001054
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001055const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001056 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001057}
1058
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001059const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001060 return remapped_configuration_;
1061}
1062
Austin Schuh6f3babe2020-01-26 20:34:50 -08001063std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001064 // Because the Node pointer will only be valid if it actually points to
1065 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001066 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001067 //
1068 // Also, note, that when ever a map is changed, the nodes in here are
1069 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001070 CHECK(remapped_configuration_ != nullptr)
1071 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001072 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001073}
Austin Schuh15649d62019-12-28 16:36:38 -08001074
Austin Schuh11d43732020-09-21 17:28:30 -07001075monotonic_clock::time_point LogReader::monotonic_start_time(
1076 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001077 State *state =
1078 states_[configuration::GetNodeIndex(configuration(), node)].get();
1079 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1080
Austin Schuh858c9f32020-08-31 16:56:12 -07001081 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001082}
1083
Austin Schuh11d43732020-09-21 17:28:30 -07001084realtime_clock::time_point LogReader::realtime_start_time(
1085 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001086 State *state =
1087 states_[configuration::GetNodeIndex(configuration(), node)].get();
1088 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1089
Austin Schuh858c9f32020-08-31 16:56:12 -07001090 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001091}
1092
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001093void LogReader::Register() {
1094 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001095 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001096 Register(event_loop_factory_unique_ptr_.get());
1097}
1098
Austin Schuh92547522019-12-28 14:33:43 -08001099void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001100 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001101 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001102 filters_ =
1103 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
1104 event_loop_factory_);
Austin Schuh92547522019-12-28 14:33:43 -08001105
Brian Silvermand90905f2020-09-23 14:42:56 -07001106 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001107 const size_t node_index =
1108 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001109 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1110 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001111
1112 // Confirm that all the parts are from the same boot if there are enough
1113 // parts to not be from the same boot.
1114 if (filtered_parts.size() > 1u) {
1115 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1116 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1117 filtered_parts[0].source_boot_uuid)
1118 << ": Found parts from different boots "
1119 << LogFileVectorToString(log_files_);
1120 }
1121 }
1122
Austin Schuh287d43d2020-12-04 20:19:33 -08001123 states_[node_index] = std::make_unique<State>(
1124 filtered_parts.size() == 0u
1125 ? nullptr
1126 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001127 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001128 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001129 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001130
1131 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001132 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001133
Austin Schuh287d43d2020-12-04 20:19:33 -08001134 for (const Node *node : configuration::GetNodes(configuration())) {
1135 const size_t node_index =
1136 configuration::GetNodeIndex(configuration(), node);
1137 State *state = states_[node_index].get();
1138 for (const Node *other_node : configuration::GetNodes(configuration())) {
1139 const size_t other_node_index =
1140 configuration::GetNodeIndex(configuration(), other_node);
1141 State *other_state = states_[other_node_index].get();
1142 if (other_state != state) {
1143 state->AddPeer(other_state);
1144 }
1145 }
1146 }
1147
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001148 // Register after making all the State objects so we can build references
1149 // between them.
1150 for (const Node *node : configuration::GetNodes(configuration())) {
1151 const size_t node_index =
1152 configuration::GetNodeIndex(configuration(), node);
1153 State *state = states_[node_index].get();
1154
1155 Register(state->event_loop());
1156 }
1157
James Kuszmaul46d82582020-05-09 19:50:09 -07001158 if (live_nodes_ == 0) {
1159 LOG(FATAL)
1160 << "Don't have logs from any of the nodes in the replay config--are "
1161 "you sure that the replay config matches the original config?";
1162 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001163
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001164 filters_->Initialize(logged_configuration());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001165
Austin Schuh858c9f32020-08-31 16:56:12 -07001166 for (std::unique_ptr<State> &state : states_) {
1167 state->SeedSortedMessages();
1168 }
1169
Austin Schuh2f8fd752020-09-01 22:38:28 -07001170 // And solve.
Austin Schuh8bd96322020-02-13 21:18:22 -08001171 UpdateOffsets();
1172
Austin Schuh2f8fd752020-09-01 22:38:28 -07001173 // We want to start the log file at the last start time of the log files
1174 // from all the nodes. Compute how long each node's simulation needs to run
1175 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001176 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001177
Austin Schuh2f8fd752020-09-01 22:38:28 -07001178 // TODO(austin): We want an "OnStart" callback for each node rather than
1179 // running until the last node.
1180
Austin Schuh8bd96322020-02-13 21:18:22 -08001181 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001182 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1183 << MaybeNodeName(state->event_loop()->node()) << "now "
1184 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001185 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1186 continue;
1187 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001188 // And start computing the start time on the distributed clock now that
1189 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001190 start_time = std::max(
1191 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001192 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001193
1194 CHECK_GE(start_time, distributed_clock::epoch())
1195 << ": Hmm, we have a node starting before the start of time. Offset "
1196 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001197
Austin Schuh6f3babe2020-01-26 20:34:50 -08001198 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1199 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001200 // nodes, and also replayed on the other nodes. This may not satisfy all
1201 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001202 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1203 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1204 const Channel *channel = logged_configuration()->channels()->Get(i);
1205 const Node *node = configuration::GetNode(
1206 configuration(), channel->source_node()->string_view());
1207
Austin Schuh8bd96322020-02-13 21:18:22 -08001208 State *state =
1209 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001210
1211 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001212 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001213
1214 event_loop_factory_->DisableForwarding(remapped_channel);
1215 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001216
1217 // If we are replaying a log, we don't want a bunch of redundant messages
1218 // from both the real message bridge and simulated message bridge.
1219 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001220 }
1221
Austin Schuhcde938c2020-02-02 17:30:07 -08001222 // While we are starting the system up, we might be relying on matching data
1223 // to timestamps on log files where the timestamp log file starts before the
1224 // data. In this case, it is reasonable to expect missing data.
1225 ignore_missing_data_ = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001226 VLOG(1) << "Running until " << start_time << " in Register";
Austin Schuh8bd96322020-02-13 21:18:22 -08001227 event_loop_factory_->RunFor(start_time.time_since_epoch());
Brian Silverman8a32ce62020-08-12 12:02:38 -07001228 VLOG(1) << "At start time";
Austin Schuhcde938c2020-02-02 17:30:07 -08001229 // Now that we are running for real, missing data means that the log file is
1230 // corrupted or went wrong.
1231 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -08001232
Austin Schuh8bd96322020-02-13 21:18:22 -08001233 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001234 // Make the RT clock be correct before handing it to the user.
1235 if (state->realtime_start_time() != realtime_clock::min_time) {
1236 state->SetRealtimeOffset(state->monotonic_start_time(),
1237 state->realtime_start_time());
1238 }
1239 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1240 << MaybeNodeName(state->event_loop()->node()) << "now "
1241 << state->monotonic_now();
1242 }
1243
1244 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001245 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -08001246 }
1247}
1248
Austin Schuh2f8fd752020-09-01 22:38:28 -07001249void LogReader::UpdateOffsets() {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001250 filters_->UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001251
1252 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001253 filters_->LogFit("Offset is");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001254 }
1255}
1256
1257message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001258 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001259 if (filters_) {
1260 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001261 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001262 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001263}
1264
Austin Schuhe309d2a2019-11-29 13:25:21 -08001265void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001266 State *state =
1267 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1268 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001269
Austin Schuh858c9f32020-08-31 16:56:12 -07001270 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001271
Tyler Chatow67ddb032020-01-12 14:30:04 -08001272 // We don't run timing reports when trying to print out logged data, because
1273 // otherwise we would end up printing out the timing reports themselves...
1274 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001275 event_loop->SkipTimingReport();
1276 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001277
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001278 for (size_t logged_channel_index = 0;
1279 logged_channel_index < logged_configuration()->channels()->size();
1280 ++logged_channel_index) {
1281 const Channel *channel = RemapChannel(
1282 event_loop,
1283 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001284
Austin Schuh2f8fd752020-09-01 22:38:28 -07001285 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -08001286 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001287
1288 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001289
1290 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1291 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001292 // We've got a message which is being forwarded to this node.
1293 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001294 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001295 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001296
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001297 // Delivery timestamps are supposed to be logged back on the source node.
1298 // Configure remote timestamps to be sent.
1299 const bool delivery_time_is_logged =
1300 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1301 channel, event_loop->node(), source_node);
1302
1303 source_state =
1304 states_[configuration::GetNodeIndex(configuration(), source_node)]
1305 .get();
1306
1307 if (delivery_time_is_logged) {
1308 remote_timestamp_sender =
1309 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001310 }
1311 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001312
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001313 state->SetChannel(
1314 logged_channel_index,
1315 configuration::ChannelIndex(event_loop->configuration(), channel),
1316 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1317 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001318 }
1319
Austin Schuh6aa77be2020-02-22 21:06:40 -08001320 // If we didn't find any log files with data in them, we won't ever get a
1321 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001322 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001323 return;
1324 }
1325
Austin Schuh858c9f32020-08-31 16:56:12 -07001326 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001327 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1328 << "at " << state->event_loop()->context().monotonic_event_time
1329 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001330 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001331 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001332 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001333 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001334 event_loop_factory_->Exit();
1335 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001336 return;
1337 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001338 if (VLOG_IS_ON(1)) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001339 filters_->LogFit("Offset was");
Austin Schuh2f8fd752020-09-01 22:38:28 -07001340 }
1341
1342 bool update_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001343 TimestampedMessage timestamped_message = state->PopOldest(&update_time);
Austin Schuh05b70472020-01-01 17:11:17 -08001344
Austin Schuhe309d2a2019-11-29 13:25:21 -08001345 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001346 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001347 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001348 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001349 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1350 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001351 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001352 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001353 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001355 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001356 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001357 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001358 << "): " << FlatbufferToJson(state->event_loop()->node())
1359 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001360 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 << state->DebugString();
1362 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001363
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001365 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001366 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001367 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
Austin Schuh858c9f32020-08-31 16:56:12 -07001368 !state->at_end()) ||
Austin Schuh287d43d2020-12-04 20:19:33 -08001369 timestamped_message.data.span().size() != 0u) {
1370 CHECK_NE(timestamped_message.data.span().size(), 0u)
Austin Schuhd32ca312020-12-13 16:38:36 -08001371 << ": Got a message without data on channel "
1372 << configuration::CleanedChannelToString(
1373 logged_configuration()->channels()->Get(
1374 timestamped_message.channel_index))
1375 << ". Forwarding entry which was not matched? Use "
1376 "--skip_missing_forwarding_entries to ignore this.";
Austin Schuh92547522019-12-28 14:33:43 -08001377
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 if (update_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001379 // Confirm that the message was sent on the sending node before the
1380 // destination node (this node). As a proxy, do this by making sure
1381 // that time on the source node is past when the message was sent.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001382 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001383 CHECK_LT(
1384 timestamped_message.monotonic_remote_time,
1385 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001386 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001387 << state->remote_node(timestamped_message.channel_index)
1388 ->name()
1389 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001390 << " while trying to send a message on "
1391 << configuration::CleanedChannelToString(
1392 logged_configuration()->channels()->Get(
1393 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001394 << " " << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001395 } else if (timestamped_message.monotonic_remote_time >=
1396 state->monotonic_remote_now(
1397 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001398 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001399 << "Check failed: timestamped_message.monotonic_remote_time < "
1400 "state->monotonic_remote_now(timestamped_message.channel_"
1401 "index) ("
1402 << timestamped_message.monotonic_remote_time << " vs. "
1403 << state->monotonic_remote_now(
1404 timestamped_message.channel_index)
1405 << ") " << state->event_loop()->node()->name()->string_view()
1406 << " to "
1407 << state->remote_node(timestamped_message.channel_index)
1408 ->name()
1409 ->string_view()
1410 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001411 << " ("
1412 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001413 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001414 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001415 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001416 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001417 timestamped_message.channel_index,
1418 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001419 << ") " << state->DebugString();
1420 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001421 }
1422
Austin Schuh15649d62019-12-28 16:36:38 -08001423 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001424 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1425 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001426
Austin Schuh2f8fd752020-09-01 22:38:28 -07001427 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001428 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001429 // TODO(austin): std::move channel_data in and make that efficient in
1430 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001431 state->Send(std::move(timestamped_message));
Austin Schuh2f8fd752020-09-01 22:38:28 -07001432 } else if (state->at_end() && !ignore_missing_data_) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001433 // We are at the end of the log file and found missing data. Finish
Austin Schuh2f8fd752020-09-01 22:38:28 -07001434 // reading the rest of the log file and call it quits. We don't want
1435 // to replay partial data.
Austin Schuh858c9f32020-08-31 16:56:12 -07001436 while (state->OldestMessageTime() != monotonic_clock::max_time) {
1437 bool update_time_dummy;
1438 state->PopOldest(&update_time_dummy);
Austin Schuh8bd96322020-02-13 21:18:22 -08001439 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001440 } else {
Austin Schuh287d43d2020-12-04 20:19:33 -08001441 CHECK(timestamped_message.data.span().data() == nullptr) << ": Nullptr";
Austin Schuh92547522019-12-28 14:33:43 -08001442 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001443 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001444 LOG(WARNING)
1445 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001446 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001447 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001448 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001449 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001450 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001451 }
1452
Austin Schuh858c9f32020-08-31 16:56:12 -07001453 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001454 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001455 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1456 << "wakeup for " << next_time << "("
1457 << state->ToDistributedClock(next_time)
1458 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001459 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001460 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001461 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1462 << "No next message, scheduling shutdown";
1463 // Set a timer up immediately after now to die. If we don't do this,
1464 // then the senders waiting on the message we just read will never get
1465 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001466 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001467 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1468 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001469 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001470 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001471
Austin Schuh2f8fd752020-09-01 22:38:28 -07001472 // Once we make this call, the current time changes. So do everything
1473 // which involves time before changing it. That especially includes
1474 // sending the message.
1475 if (update_time) {
1476 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1477 << "updating offsets";
1478
1479 std::vector<aos::monotonic_clock::time_point> before_times;
1480 before_times.resize(states_.size());
1481 std::transform(states_.begin(), states_.end(), before_times.begin(),
1482 [](const std::unique_ptr<State> &state) {
1483 return state->monotonic_now();
1484 });
1485
Austin Schuh8bd96322020-02-13 21:18:22 -08001486 UpdateOffsets();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001487 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Now is now "
1488 << state->monotonic_now();
1489
Austin Schuh2f8fd752020-09-01 22:38:28 -07001490 // TODO(austin): We should be perfect.
1491 const std::chrono::nanoseconds kTolerance{3};
1492 if (!FLAGS_skip_order_validation) {
1493 CHECK_GE(next_time, state->monotonic_now())
Austin Schuh188eabe2020-12-29 23:41:13 -08001494 << ": Time skipped the next event, just sent "
1495 << timestamped_message << ", sending next " << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001496
1497 for (size_t i = 0; i < states_.size(); ++i) {
1498 CHECK_GE(states_[i]->monotonic_now(), before_times[i] - kTolerance)
1499 << ": Time changed too much on node "
1500 << MaybeNodeName(states_[i]->event_loop()->node());
1501 CHECK_LE(states_[i]->monotonic_now(), before_times[i] + kTolerance)
1502 << ": Time changed too much on node "
Austin Schuhc9049732020-12-21 22:27:15 -08001503 << MaybeNodeName(states_[i]->event_loop()->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -07001504 }
1505 } else {
1506 if (next_time < state->monotonic_now()) {
1507 LOG(WARNING) << "Check failed: next_time >= "
1508 "state->monotonic_now() ("
1509 << next_time << " vs. " << state->monotonic_now()
Austin Schuh188eabe2020-12-29 23:41:13 -08001510 << "): Time skipped the next event, just sent "
1511 << timestamped_message << ", sending next "
1512 << state->PeekOldest();
Austin Schuh2f8fd752020-09-01 22:38:28 -07001513 }
1514 for (size_t i = 0; i < states_.size(); ++i) {
Austin Schuh724032b2020-12-18 22:54:59 -08001515 if (states_[i]->monotonic_now() < before_times[i] - kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001516 LOG(WARNING) << "Check failed: "
1517 "states_[i]->monotonic_now() "
1518 ">= before_times[i] - kTolerance ("
1519 << states_[i]->monotonic_now() << " vs. "
1520 << before_times[i] - kTolerance
1521 << ") : Time changed too much on node "
1522 << MaybeNodeName(states_[i]->event_loop()->node());
1523 }
Austin Schuh724032b2020-12-18 22:54:59 -08001524 if (states_[i]->monotonic_now() > before_times[i] + kTolerance) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001525 LOG(WARNING) << "Check failed: "
1526 "states_[i]->monotonic_now() "
1527 "<= before_times[i] + kTolerance ("
1528 << states_[i]->monotonic_now() << " vs. "
Austin Schuh724032b2020-12-18 22:54:59 -08001529 << before_times[i] + kTolerance
Austin Schuh2f8fd752020-09-01 22:38:28 -07001530 << ") : Time changed too much on node "
1531 << MaybeNodeName(states_[i]->event_loop()->node());
1532 }
1533 }
1534 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001535 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001536
1537 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1538 << state->event_loop()->context().monotonic_event_time << " now "
1539 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001540 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001541
Austin Schuh6f3babe2020-01-26 20:34:50 -08001542 ++live_nodes_;
1543
Austin Schuh858c9f32020-08-31 16:56:12 -07001544 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1545 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001546 }
1547}
1548
1549void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001550 // Make sure that things get destroyed in the correct order, rather than
1551 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001552 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001553 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001554 }
Austin Schuh92547522019-12-28 14:33:43 -08001555
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001556 event_loop_factory_unique_ptr_.reset();
1557 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001558}
1559
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001560void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001561 std::string_view add_prefix,
1562 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001563 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1564 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1565 if (channel->name()->str() == name &&
1566 channel->type()->string_view() == type) {
1567 CHECK_EQ(0u, remapped_channels_.count(ii))
1568 << "Already remapped channel "
1569 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001570 RemappedChannel remapped_channel;
1571 remapped_channel.remapped_name =
1572 std::string(add_prefix) + std::string(name);
1573 remapped_channel.new_type = new_type;
1574 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001575 VLOG(1) << "Remapping channel "
1576 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001577 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001578 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001579 return;
1580 }
1581 }
1582 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1583 << type;
1584}
1585
Austin Schuh01b4c352020-09-21 23:09:39 -07001586void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1587 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001588 std::string_view add_prefix,
1589 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001590 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1591 const Channel *remapped_channel =
1592 configuration::GetChannel(logged_configuration(), name, type, "", node);
1593 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1594 << "\", \"type\": \"" << type << "\"}";
1595 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1596 << "\"}";
1597 VLOG(1) << "Remapped "
1598 << aos::configuration::StrippedChannelToString(remapped_channel);
1599
1600 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1601 // we want it to degrade if the heuristics fail to just work.
1602 //
1603 // The easiest way to do this is going to be incredibly specific and verbose.
1604 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1605 // /original/0/spray. Then, create a map from /original/spray to
1606 // /original/0/spray for just the type we were asked for.
1607 if (name != remapped_channel->name()->string_view()) {
1608 MapT new_map;
1609 new_map.match = std::make_unique<ChannelT>();
1610 new_map.match->name = absl::StrCat(add_prefix, name);
1611 new_map.match->type = type;
1612 if (node != nullptr) {
1613 new_map.match->source_node = node->name()->str();
1614 }
1615 new_map.rename = std::make_unique<ChannelT>();
1616 new_map.rename->name =
1617 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1618 maps_.emplace_back(std::move(new_map));
1619 }
1620
1621 const size_t channel_index =
1622 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1623 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1624 << "Already remapped channel "
1625 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001626
1627 RemappedChannel remapped_channel_struct;
1628 remapped_channel_struct.remapped_name =
1629 std::string(add_prefix) +
1630 std::string(remapped_channel->name()->string_view());
1631 remapped_channel_struct.new_type = new_type;
1632 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001633 MakeRemappedConfig();
1634}
1635
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001636void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001637 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001638 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001639 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001640 << ": Can't change the mapping after the events are scheduled.";
1641 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001642 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001643
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001644 // If no remapping occurred and we are using the original config, then there
1645 // is nothing interesting to do here.
1646 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001647 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001648 return;
1649 }
1650 // Config to copy Channel definitions from. Use the specified
1651 // replay_configuration_ if it has been provided.
1652 const Configuration *const base_config = replay_configuration_ == nullptr
1653 ? logged_configuration()
1654 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001655
1656 // Create a config with all the channels, but un-sorted/merged. Collect up
1657 // the schemas while we do this. Call MergeConfiguration to sort everything,
1658 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001659
1660 // This is the builder that we use for the config containing all the new
1661 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001662 flatbuffers::FlatBufferBuilder fbb;
1663 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001664 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001665
1666 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1667 << ": Merging logic needs to be updated when the number of channel "
1668 "fields changes.";
1669
1670 // List of schemas.
1671 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1672 // Make sure our new RemoteMessage schema is in there for old logs without it.
1673 schema_map.insert(std::make_pair(
1674 RemoteMessage::GetFullyQualifiedName(),
1675 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1676 message_bridge::RemoteMessageSchema()))));
1677
1678 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001679 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001680 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001681 base_config, logged_configuration()->channels()->Get(pair.first), "",
1682 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001683 channel_offsets.emplace_back(
1684 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001685 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001686
Austin Schuh0de30f32020-12-06 12:44:28 -08001687 // Now reconstruct the original channels, translating types as needed
1688 for (const Channel *c : *base_config->channels()) {
1689 // Search for a mapping channel.
1690 std::string_view new_type = "";
1691 for (auto &pair : remapped_channels_) {
1692 const Channel *const remapped_channel =
1693 logged_configuration()->channels()->Get(pair.first);
1694 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1695 remapped_channel->type()->string_view() == c->type()->string_view()) {
1696 new_type = pair.second.new_type;
1697 break;
1698 }
1699 }
1700
1701 // Copy everything over.
1702 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1703
1704 // Add the schema if it doesn't exist.
1705 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1706 CHECK(c->has_schema());
1707 schema_map.insert(std::make_pair(c->type()->string_view(),
1708 RecursiveCopyFlatBuffer(c->schema())));
1709 }
1710 }
1711
1712 // The MergeConfiguration API takes a vector, not a map. Convert.
1713 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1714 while (!schema_map.empty()) {
1715 schemas.emplace_back(std::move(schema_map.begin()->second));
1716 schema_map.erase(schema_map.begin());
1717 }
1718
1719 // Create the Configuration containing the new channels that we want to add.
1720 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1721 channels_offset =
1722 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1723
1724 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001725 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001726 if (base_config->maps()) {
1727 for (const Map *map : *base_config->maps()) {
1728 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1729 }
1730 }
1731
1732 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001733 for (const MapT &map : maps_) {
1734 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001735 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001736 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001737 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001738 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001739 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001740 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1741 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001742 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001743 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001744 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001745 match_builder.add_name(match_name_offset);
1746 match_builder.add_type(match_type_offset);
1747 if (!map.match->source_node.empty()) {
1748 match_builder.add_source_node(match_source_node_offset);
1749 }
1750 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1751
Austin Schuh0de30f32020-12-06 12:44:28 -08001752 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001753 rename_builder.add_name(rename_name_offset);
1754 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1755
Austin Schuh0de30f32020-12-06 12:44:28 -08001756 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001757 map_builder.add_match(match_offset);
1758 map_builder.add_rename(rename_offset);
1759 map_offsets.emplace_back(map_builder.Finish());
1760 }
1761
Austin Schuh0de30f32020-12-06 12:44:28 -08001762 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1763 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001764
Austin Schuh0de30f32020-12-06 12:44:28 -08001765 // And copy everything else over.
1766 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1767 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1768
1769 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1770 applications_offset =
1771 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1772
1773 // Now insert everything else in unmodified.
1774 ConfigurationBuilder configuration_builder(fbb);
1775 if (!channels_offset.IsNull()) {
1776 configuration_builder.add_channels(channels_offset);
1777 }
1778 if (!maps_offsets.IsNull()) {
1779 configuration_builder.add_maps(maps_offsets);
1780 }
1781 if (!nodes_offset.IsNull()) {
1782 configuration_builder.add_nodes(nodes_offset);
1783 }
1784 if (!applications_offset.IsNull()) {
1785 configuration_builder.add_applications(applications_offset);
1786 }
1787
1788 if (base_config->has_channel_storage_duration()) {
1789 configuration_builder.add_channel_storage_duration(
1790 base_config->channel_storage_duration());
1791 }
1792
1793 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1794 << ": Merging logic needs to be updated when the number of configuration "
1795 "fields changes.";
1796
1797 fbb.Finish(configuration_builder.Finish());
1798
1799 // Clean it up and return it! By using MergeConfiguration here, we'll
1800 // actually get a deduplicated config for free too.
1801 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1802 configuration::MergeConfiguration(
1803 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1804
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001805 remapped_configuration_buffer_ =
1806 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001807 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001808
1809 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001810
1811 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001812}
1813
Austin Schuh6f3babe2020-01-26 20:34:50 -08001814const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1815 const Channel *channel) {
1816 std::string_view channel_name = channel->name()->string_view();
1817 std::string_view channel_type = channel->type()->string_view();
1818 const int channel_index =
1819 configuration::ChannelIndex(logged_configuration(), channel);
1820 // If the channel is remapped, find the correct channel name to use.
1821 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001822 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001823 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001824 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001825 }
1826
Austin Schuhee711052020-08-24 16:06:09 -07001827 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001828 const Channel *remapped_channel = configuration::GetChannel(
1829 event_loop->configuration(), channel_name, channel_type,
1830 event_loop->name(), event_loop->node());
1831
1832 CHECK(remapped_channel != nullptr)
1833 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1834 << channel_type << "\"} because it is not in the provided configuration.";
1835
1836 return remapped_channel;
1837}
1838
Austin Schuh287d43d2020-12-04 20:19:33 -08001839LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1840 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1841
1842void LogReader::State::AddPeer(State *peer) {
1843 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1844 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1845 }
1846}
Austin Schuh858c9f32020-08-31 16:56:12 -07001847
1848EventLoop *LogReader::State::SetNodeEventLoopFactory(
1849 NodeEventLoopFactory *node_event_loop_factory) {
1850 node_event_loop_factory_ = node_event_loop_factory;
1851 event_loop_unique_ptr_ =
1852 node_event_loop_factory_->MakeEventLoop("log_reader");
1853 return event_loop_unique_ptr_.get();
1854}
1855
1856void LogReader::State::SetChannelCount(size_t count) {
1857 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001858 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001859 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001860 channel_source_state_.resize(count);
1861 factory_channel_index_.resize(count);
1862 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001863}
1864
1865void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001866 size_t logged_channel_index, size_t factory_channel_index,
1867 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001868 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001869 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001870 channels_[logged_channel_index] = std::move(sender);
1871 filters_[logged_channel_index] = filter;
1872 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1873
1874 if (source_state) {
1875 channel_source_state_[logged_channel_index] = source_state;
1876
1877 if (remote_timestamp_sender != nullptr) {
1878 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001879 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001880 }
1881 }
1882
1883 factory_channel_index_[logged_channel_index] = factory_channel_index;
1884}
1885
Austin Schuh287d43d2020-12-04 20:19:33 -08001886bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1887 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001888 uint32_t remote_queue_index = 0xffffffff;
1889
Austin Schuh287d43d2020-12-04 20:19:33 -08001890 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001891 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001892 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1893 ->queue_index_map_[timestamped_message.channel_index]
1894 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001895
Austin Schuh9942bae2021-01-07 22:06:44 -08001896 struct SentTimestamp {
1897 monotonic_clock::time_point monotonic_event_time;
1898 uint32_t queue_index;
1899 } search;
1900
Austin Schuh287d43d2020-12-04 20:19:33 -08001901 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001902 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001903
1904 // Find the sent time if available.
1905 auto element = std::lower_bound(
1906 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001907 [](ContiguousSentTimestamp a, SentTimestamp b) {
1908 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001909 return true;
1910 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001911 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001912 return false;
1913 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001914
1915 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001916 return true;
1917 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001918 if (a.starting_queue_index >= b.queue_index) {
1919 return false;
1920 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001921
Austin Schuh9942bae2021-01-07 22:06:44 -08001922 // If it isn't clearly below or above, it is below. Since we return
1923 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001924 return false;
1925 });
1926
1927 // TODO(austin): Be a bit more principled here, but we will want to do that
1928 // after the logger rewrite. We hit this when one node finishes, but the
1929 // other node isn't done yet. So there is no send time, but there is a
1930 // receive time.
1931 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001932 CHECK_GE(timestamped_message.monotonic_remote_time,
1933 element->starting_monotonic_event_time);
1934 CHECK_LE(timestamped_message.monotonic_remote_time,
1935 element->ending_monotonic_event_time);
1936 CHECK_GE(timestamped_message.remote_queue_index,
1937 element->starting_queue_index);
1938 CHECK_LE(timestamped_message.remote_queue_index,
1939 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001940
Austin Schuh9942bae2021-01-07 22:06:44 -08001941 remote_queue_index = timestamped_message.remote_queue_index +
1942 element->actual_queue_index -
1943 element->starting_queue_index;
1944 } else {
1945 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001946 }
1947 }
1948
1949 // Send! Use the replayed queue index here instead of the logged queue index
1950 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001951 const bool sent = sender->Send(
1952 timestamped_message.data.message().data()->Data(),
1953 timestamped_message.data.message().data()->size(),
1954 timestamped_message.monotonic_remote_time,
1955 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001956 if (!sent) return false;
1957
Austin Schuh287d43d2020-12-04 20:19:33 -08001958 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001959 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1960 // Nothing here, start a range with 0 length.
1961 ContiguousSentTimestamp timestamp;
1962 timestamp.starting_monotonic_event_time =
1963 timestamp.ending_monotonic_event_time =
1964 timestamped_message.monotonic_event_time;
1965 timestamp.starting_queue_index = timestamp.ending_queue_index =
1966 timestamped_message.queue_index;
1967 timestamp.actual_queue_index = sender->sent_queue_index();
1968 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1969 timestamp);
1970 } else {
1971 // We've got something. See if the next timestamp is still contiguous. If
1972 // so, grow it.
1973 ContiguousSentTimestamp *back =
1974 &queue_index_map_[timestamped_message.channel_index]->back();
1975 if ((back->starting_queue_index - back->actual_queue_index) ==
1976 (timestamped_message.queue_index - sender->sent_queue_index())) {
1977 back->ending_queue_index = timestamped_message.queue_index;
1978 back->ending_monotonic_event_time =
1979 timestamped_message.monotonic_event_time;
1980 } else {
1981 // Otherwise, make a new one.
1982 ContiguousSentTimestamp timestamp;
1983 timestamp.starting_monotonic_event_time =
1984 timestamp.ending_monotonic_event_time =
1985 timestamped_message.monotonic_event_time;
1986 timestamp.starting_queue_index = timestamp.ending_queue_index =
1987 timestamped_message.queue_index;
1988 timestamp.actual_queue_index = sender->sent_queue_index();
1989 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1990 timestamp);
1991 }
1992 }
1993
1994 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1995 // queue index diverge a couple of elements, which would be a very small
1996 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001997 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1998 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001999 flatbuffers::FlatBufferBuilder fbb;
2000 fbb.ForceDefaults(true);
Austin Schuh315b96b2020-12-11 21:21:12 -08002001 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
Austin Schuh969cd602021-01-03 00:09:45 -08002002 fbb.CreateString(event_loop_->boot_uuid().string_view());
Austin Schuh315b96b2020-12-11 21:21:12 -08002003
Austin Schuh969cd602021-01-03 00:09:45 -08002004 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002005
2006 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08002007 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002008
2009 // Swap the remote and sent metrics. They are from the sender's
2010 // perspective, not the receiver's perspective.
2011 message_header_builder.add_monotonic_sent_time(
2012 sender->monotonic_sent_time().time_since_epoch().count());
2013 message_header_builder.add_realtime_sent_time(
2014 sender->realtime_sent_time().time_since_epoch().count());
2015 message_header_builder.add_queue_index(sender->sent_queue_index());
2016
2017 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002018 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002019 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08002020 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002021
2022 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002023 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002024
Austin Schuh969cd602021-01-03 00:09:45 -08002025 fbb.Finish(message_header_builder.Finish());
2026
2027 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2028 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
2029 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002030 }
2031
2032 return true;
2033}
2034
Austin Schuh969cd602021-01-03 00:09:45 -08002035LogReader::RemoteMessageSender::RemoteMessageSender(
2036 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2037 : event_loop_(event_loop),
2038 sender_(std::move(sender)),
2039 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2040
2041void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2042 if (remote_timestamps_.empty()) {
2043 CHECK_NOTNULL(timer_);
2044 timer_->Disable();
2045 scheduled_time_ = monotonic_clock::min_time;
2046 return;
2047 }
2048
2049 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2050 CHECK_NOTNULL(timer_);
2051 timer_->Setup(
2052 remote_timestamps_.front().monotonic_timestamp_time);
2053 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
2054 }
2055}
2056
2057void LogReader::RemoteMessageSender::Send(
2058 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
2059 monotonic_clock::time_point monotonic_timestamp_time) {
2060 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
2061 // resend the timestamp at the correct time, or we don't and can send it
2062 // immediately.
2063 if (monotonic_timestamp_time == monotonic_clock::min_time) {
2064 CHECK(remote_timestamps_.empty())
2065 << ": Unsupported mix of timestamps and no timestamps.";
2066 sender_.Send(std::move(remote_message));
2067 } else {
2068 remote_timestamps_.emplace_back(std::move(remote_message),
2069 monotonic_timestamp_time);
2070 ScheduleTimestamp();
2071 }
2072}
2073
2074void LogReader::RemoteMessageSender::SendTimestamp() {
2075 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_);
2076 CHECK(!remote_timestamps_.empty());
2077
2078 // Send out all timestamps at the currently scheduled time.
2079 while (remote_timestamps_.front().monotonic_timestamp_time ==
2080 scheduled_time_) {
2081 sender_.Send(std::move(remote_timestamps_.front().remote_message));
2082 remote_timestamps_.pop_front();
2083 if (remote_timestamps_.empty()) {
2084 break;
2085 }
2086 }
2087 scheduled_time_ = monotonic_clock::min_time;
2088
2089 ScheduleTimestamp();
2090}
2091
2092LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002093 const Node *delivered_node) {
2094 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2095
2096 if (sender == remote_timestamp_senders_map_.end()) {
Austin Schuh969cd602021-01-03 00:09:45 -08002097 sender =
2098 remote_timestamp_senders_map_
2099 .emplace(delivered_node,
2100 std::make_unique<RemoteMessageSender>(
2101 event_loop()->MakeSender<RemoteMessage>(absl::StrCat(
2102 "/aos/remote_timestamps/",
2103 delivered_node->name()->string_view())),
2104 event_loop()))
2105 .first;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002106 }
2107
Austin Schuh969cd602021-01-03 00:09:45 -08002108 return sender->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002109}
2110
Austin Schuh188eabe2020-12-29 23:41:13 -08002111const TimestampedMessage &LogReader::State::PeekOldest() {
2112 return std::get<0>(sorted_messages_.front());
2113}
2114
Austin Schuh287d43d2020-12-04 20:19:33 -08002115TimestampedMessage LogReader::State::PopOldest(bool *update_time) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002116 CHECK_GT(sorted_messages_.size(), 0u);
2117
Austin Schuh287d43d2020-12-04 20:19:33 -08002118 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002119 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002120 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002121 << std::get<0>(result).monotonic_event_time;
2122 sorted_messages_.pop_front();
2123 SeedSortedMessages();
2124
Austin Schuh287d43d2020-12-04 20:19:33 -08002125 if (std::get<1>(result) != nullptr) {
2126 *update_time = std::get<1>(result)->Pop(
Austin Schuh2f8fd752020-09-01 22:38:28 -07002127 event_loop_->node(), std::get<0>(result).monotonic_event_time);
2128 } else {
2129 *update_time = false;
2130 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002131 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002132}
2133
2134monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2135 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002136 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002137 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2138 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2139 }
2140
Austin Schuh287d43d2020-12-04 20:19:33 -08002141 TimestampedMessage *m =
2142 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2143 if (m == nullptr) {
2144 return monotonic_clock::max_time;
2145 }
2146 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002147}
2148
2149void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002150 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002151 const aos::monotonic_clock::time_point end_queue_time =
2152 (sorted_messages_.size() > 0
2153 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002154 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002155 chrono::duration_cast<chrono::seconds>(
2156 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002157
2158 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002159 TimestampedMessage *m = timestamp_mapper_->Front();
2160 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002161 return;
2162 }
2163 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002164 // Stop placing sorted messages on the list once we have
2165 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2166 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002167 if (end_queue_time <
2168 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2169 return;
2170 }
2171 }
2172
Austin Schuh2f8fd752020-09-01 22:38:28 -07002173 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2174
Austin Schuh287d43d2020-12-04 20:19:33 -08002175 TimestampedMessage timestamped_message = std::move(*m);
2176 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002177
Austin Schuh2f8fd752020-09-01 22:38:28 -07002178 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002179 if (timestamped_message.monotonic_remote_time !=
2180 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002181 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002182 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002183
2184 CHECK(filter != nullptr);
2185
2186 // Call the correct method depending on if we are the forward or
2187 // reverse direction here.
2188 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002189 timestamped_message.monotonic_event_time,
2190 timestamped_message.monotonic_remote_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002191 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002192 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002193 }
2194}
2195
2196void LogReader::State::Deregister() {
2197 for (size_t i = 0; i < channels_.size(); ++i) {
2198 channels_[i].reset();
2199 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002200 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002201 event_loop_unique_ptr_.reset();
2202 event_loop_ = nullptr;
2203 timer_handler_ = nullptr;
2204 node_event_loop_factory_ = nullptr;
2205}
2206
Austin Schuhe309d2a2019-11-29 13:25:21 -08002207} // namespace logger
2208} // namespace aos