blob: 7e822de0c0f421e485782e7cd68349d88ef46223 [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 Schuh816e5d62021-01-05 23:42:20 -0800336 node_state_[node_index].log_file_header = MakeHeader(node, config_sha256);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700337 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800338
Austin Schuh2f8fd752020-09-01 22:38:28 -0700339 // Grab data from each channel right before we declare the log file started
340 // so we can capture the latest message on each channel. This lets us have
341 // non periodic messages with configuration that now get logged.
342 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700343 const auto start = event_loop_->monotonic_now();
344 const bool got_new = f.fetcher->Fetch();
345 const auto end = event_loop_->monotonic_now();
346 RecordFetchResult(start, end, got_new, &f);
347
348 // If there is a message, we want to write it.
349 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700350 }
351
352 // Clear out any old timestamps in case we are re-starting logging.
353 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800354 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
355 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700356 }
357
358 WriteHeader();
359
360 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
361 << " start_time " << last_synchronized_time_;
362
Austin Schuh315b96b2020-12-11 21:21:12 -0800363 // Force logging up until the start of the log file now, so the messages at
364 // the start are always ordered before the rest of the messages.
365 // Note: this ship may have already sailed, but we don't have to make it
366 // worse.
367 // TODO(austin): Test...
368 LogUntil(last_synchronized_time_);
369
Austin Schuh2f8fd752020-09-01 22:38:28 -0700370 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
371 polling_period_);
372}
373
Brian Silverman1f345222020-09-24 21:14:48 -0700374std::unique_ptr<LogNamer> Logger::StopLogging(
375 aos::monotonic_clock::time_point end_time) {
376 CHECK(log_namer_) << ": Not logging right now";
377
378 if (end_time != aos::monotonic_clock::min_time) {
379 LogUntil(end_time);
380 }
381 timer_handler_->Disable();
382
383 for (FetcherStruct &f : fetchers_) {
384 f.writer = nullptr;
385 f.timestamp_writer = nullptr;
386 f.contents_writer = nullptr;
387 }
388 node_state_.clear();
389
Brian Silvermanae7c0332020-09-30 16:58:23 -0700390 log_event_uuid_ = UUID::Zero();
391 log_start_uuid_ = std::string();
392
Brian Silverman1f345222020-09-24 21:14:48 -0700393 return std::move(log_namer_);
394}
395
Austin Schuhfa895892020-01-07 20:07:41 -0800396void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700397 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700398 server_statistics_fetcher_.Fetch();
399 }
400
401 aos::monotonic_clock::time_point monotonic_start_time =
402 event_loop_->monotonic_now();
403 aos::realtime_clock::time_point realtime_start_time =
404 event_loop_->realtime_now();
405
406 // We need to pick a point in time to declare the log file "started". This
407 // starts here. It needs to be after everything is fetched so that the
408 // fetchers are all pointed at the most recent message before the start
409 // time.
410 last_synchronized_time_ = monotonic_start_time;
411
Austin Schuh6f3babe2020-01-26 20:34:50 -0800412 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700413 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700414 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
415 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800416 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800417 }
418}
Austin Schuh8bd96322020-02-13 21:18:22 -0800419
Austin Schuh315b96b2020-12-11 21:21:12 -0800420void Logger::MaybeWriteHeader(int node_index) {
421 if (configuration::MultiNode(configuration_)) {
422 return MaybeWriteHeader(node_index,
423 configuration_->nodes()->Get(node_index));
424 } else {
425 return MaybeWriteHeader(node_index, nullptr);
426 }
427}
428
429void Logger::MaybeWriteHeader(int node_index, const Node *node) {
430 // This function is responsible for writing the header when the header both
431 // has valid data, and when it needs to be written.
432 if (node_state_[node_index].header_written &&
433 node_state_[node_index].header_valid) {
434 // The header has been written and is valid, nothing to do.
435 return;
436 }
437 if (!node_state_[node_index].has_source_node_boot_uuid) {
438 // Can't write a header if we don't have the boot UUID.
439 return;
440 }
441
442 // WriteHeader writes the first header in a log file. We want to do this only
443 // once.
444 //
445 // Rotate rewrites the same header with a new part ID, but keeps the same part
446 // UUID. We don't want that when things reboot, because that implies that
447 // parts go together across a reboot.
448 //
449 // Reboot resets the parts UUID. So, once we've written a header the first
450 // time, we want to use Reboot to rotate the log and reset the parts UUID.
451 //
452 // header_valid is cleared whenever the remote reboots.
453 if (node_state_[node_index].header_written) {
454 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
455 } else {
456 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
457
458 node_state_[node_index].header_written = true;
459 }
460 node_state_[node_index].header_valid = true;
461}
462
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700464 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700465 server_statistics_fetcher_.Fetch();
466 } else {
467 return;
468 }
469
470 if (server_statistics_fetcher_.get() == nullptr) {
471 return;
472 }
473
474 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700475 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700476 if (MaybeUpdateTimestamp(
477 node, node_index,
478 server_statistics_fetcher_.context().monotonic_event_time,
479 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800480 CHECK(node_state_[node_index].header_written);
481 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700482 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800483 } else {
484 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700485 }
486 }
487}
488
Austin Schuh315b96b2020-12-11 21:21:12 -0800489void Logger::SetStartTime(
490 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
491 aos::realtime_clock::time_point realtime_start_time,
492 aos::monotonic_clock::time_point logger_monotonic_start_time,
493 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700494 node_state_[node_index].monotonic_start_time = monotonic_start_time;
495 node_state_[node_index].realtime_start_time = realtime_start_time;
496 node_state_[node_index]
497 .log_file_header.mutable_message()
498 ->mutate_monotonic_start_time(
499 std::chrono::duration_cast<std::chrono::nanoseconds>(
500 monotonic_start_time.time_since_epoch())
501 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800502
503 // Add logger start times if they are available in the log file header.
504 if (node_state_[node_index]
505 .log_file_header.mutable_message()
506 ->has_logger_monotonic_start_time()) {
507 node_state_[node_index]
508 .log_file_header.mutable_message()
509 ->mutate_logger_monotonic_start_time(
510 std::chrono::duration_cast<std::chrono::nanoseconds>(
511 logger_monotonic_start_time.time_since_epoch())
512 .count());
513 }
514
515 if (node_state_[node_index]
516 .log_file_header.mutable_message()
517 ->has_logger_realtime_start_time()) {
518 node_state_[node_index]
519 .log_file_header.mutable_message()
520 ->mutate_logger_realtime_start_time(
521 std::chrono::duration_cast<std::chrono::nanoseconds>(
522 logger_realtime_start_time.time_since_epoch())
523 .count());
524 }
525
Austin Schuh2f8fd752020-09-01 22:38:28 -0700526 if (node_state_[node_index]
527 .log_file_header.mutable_message()
528 ->has_realtime_start_time()) {
529 node_state_[node_index]
530 .log_file_header.mutable_message()
531 ->mutate_realtime_start_time(
532 std::chrono::duration_cast<std::chrono::nanoseconds>(
533 realtime_start_time.time_since_epoch())
534 .count());
535 }
536}
537
538bool Logger::MaybeUpdateTimestamp(
539 const Node *node, int node_index,
540 aos::monotonic_clock::time_point monotonic_start_time,
541 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700542 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700543 if (node_state_[node_index].monotonic_start_time !=
544 monotonic_clock::min_time) {
545 return false;
546 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800547 if (event_loop_->node() == node ||
548 !configuration::MultiNode(configuration_)) {
549 // There are no offsets to compute for ourself, so always succeed.
550 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
551 monotonic_start_time, realtime_start_time);
552 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700553 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800554 } else if (server_statistics_fetcher_.get() != nullptr) {
555 // We must be a remote node now. Look for the connection and see if it is
556 // connected.
557
558 for (const message_bridge::ServerConnection *connection :
559 *server_statistics_fetcher_->connections()) {
560 if (connection->node()->name()->string_view() !=
561 node->name()->string_view()) {
562 continue;
563 }
564
565 if (connection->state() != message_bridge::State::CONNECTED) {
566 VLOG(1) << node->name()->string_view()
567 << " is not connected, can't start it yet.";
568 break;
569 }
570
571 // Update the boot UUID as soon as we know we are connected.
572 if (!connection->has_boot_uuid()) {
573 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
574 break;
575 }
576
577 if (!node_state_[node_index].has_source_node_boot_uuid ||
578 node_state_[node_index].source_node_boot_uuid !=
579 connection->boot_uuid()->string_view()) {
580 node_state_[node_index].SetBootUUID(
581 connection->boot_uuid()->string_view());
582 }
583
584 if (!connection->has_monotonic_offset()) {
585 VLOG(1) << "Missing monotonic offset for setting start time for node "
586 << aos::FlatbufferToJson(node);
587 break;
588 }
589
590 // Found it and it is connected. Compensate and go.
591 SetStartTime(node_index,
592 monotonic_start_time +
593 std::chrono::nanoseconds(connection->monotonic_offset()),
594 realtime_start_time, monotonic_start_time,
595 realtime_start_time);
596 return true;
597 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700598 }
599 return false;
600}
601
602aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
Austin Schuh8c399962020-12-25 21:51:45 -0800603 const Node *node, std::string_view config_sha256) {
Austin Schuhfa895892020-01-07 20:07:41 -0800604 // Now write the header with this timestamp in it.
605 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800606 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800607
Austin Schuh8c399962020-12-25 21:51:45 -0800608 flatbuffers::Offset<aos::Configuration> configuration_offset;
609 if (!separate_config_) {
610 configuration_offset = CopyFlatBuffer(configuration_, &fbb);
611 } else {
612 CHECK(!config_sha256.empty());
613 }
Austin Schuhfa895892020-01-07 20:07:41 -0800614
Brian Silvermanae7c0332020-09-30 16:58:23 -0700615 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700616 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800617
Brian Silvermanae7c0332020-09-30 16:58:23 -0700618 CHECK(log_event_uuid_ != UUID::Zero());
619 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
620 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700621
Brian Silvermanae7c0332020-09-30 16:58:23 -0700622 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
623 fbb.CreateString(logger_instance_uuid_.string_view());
624
625 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
626 if (!log_start_uuid_.empty()) {
627 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
628 }
629
Austin Schuh8c399962020-12-25 21:51:45 -0800630 flatbuffers::Offset<flatbuffers::String> config_sha256_offset;
631 if (!config_sha256.empty()) {
632 config_sha256_offset = fbb.CreateString(config_sha256);
633 }
634
Austin Schuh315b96b2020-12-11 21:21:12 -0800635 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
636 fbb.CreateString(event_loop_->boot_uuid().string_view());
637
638 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
639 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700640
641 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700642 fbb.CreateString("00000000-0000-4000-8000-000000000000");
643
Austin Schuhfa895892020-01-07 20:07:41 -0800644 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700645 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700646
Austin Schuh0c297012020-09-16 18:41:59 -0700647 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800648 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
649 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800650 }
651
652 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
653
Austin Schuh64fab802020-09-09 22:47:47 -0700654 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800655
656 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800657 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800658 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700659 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800660 }
661
Austin Schuh8c399962020-12-25 21:51:45 -0800662 if (!configuration_offset.IsNull()) {
663 log_file_header_builder.add_configuration(configuration_offset);
664 }
Austin Schuhfa895892020-01-07 20:07:41 -0800665 // The worst case theoretical out of order is the polling period times 2.
666 // One message could get logged right after the boundary, but be for right
667 // before the next boundary. And the reverse could happen for another
668 // message. Report back 3x to be extra safe, and because the cost isn't
669 // huge on the read side.
670 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700671 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800672
673 log_file_header_builder.add_monotonic_start_time(
674 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700675 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800676 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700677 if (node == event_loop_->node()) {
678 log_file_header_builder.add_realtime_start_time(
679 std::chrono::duration_cast<std::chrono::nanoseconds>(
680 realtime_clock::min_time.time_since_epoch())
681 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800682 } else {
683 log_file_header_builder.add_logger_monotonic_start_time(
684 std::chrono::duration_cast<std::chrono::nanoseconds>(
685 monotonic_clock::min_time.time_since_epoch())
686 .count());
687 log_file_header_builder.add_logger_realtime_start_time(
688 std::chrono::duration_cast<std::chrono::nanoseconds>(
689 realtime_clock::min_time.time_since_epoch())
690 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800691 }
692
Brian Silvermanae7c0332020-09-30 16:58:23 -0700693 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
694 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
695 if (!log_start_uuid_offset.IsNull()) {
696 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
697 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800698 log_file_header_builder.add_logger_node_boot_uuid(
699 logger_node_boot_uuid_offset);
700 log_file_header_builder.add_source_node_boot_uuid(
701 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700702
703 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
704 log_file_header_builder.add_parts_index(0);
705
Austin Schuh8c399962020-12-25 21:51:45 -0800706 log_file_header_builder.add_configuration_sha256(0);
707
708 if (!config_sha256_offset.IsNull()) {
709 log_file_header_builder.add_configuration_sha256(config_sha256_offset);
710 }
711
Austin Schuh2f8fd752020-09-01 22:38:28 -0700712 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800713 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
714 fbb.Release());
715
716 CHECK(result.Verify()) << ": Built a corrupted header.";
717
718 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700719}
720
Brian Silvermancb805822020-10-06 17:43:35 -0700721void Logger::ResetStatisics() {
722 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
723 max_message_fetch_time_channel_ = -1;
724 max_message_fetch_time_size_ = -1;
725 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
726 total_message_fetch_count_ = 0;
727 total_message_fetch_bytes_ = 0;
728 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
729 total_nop_fetch_count_ = 0;
730 max_copy_time_ = std::chrono::nanoseconds::zero();
731 max_copy_time_channel_ = -1;
732 max_copy_time_size_ = -1;
733 total_copy_time_ = std::chrono::nanoseconds::zero();
734 total_copy_count_ = 0;
735 total_copy_bytes_ = 0;
736}
737
Austin Schuh2f8fd752020-09-01 22:38:28 -0700738void Logger::Rotate() {
739 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700740 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700741 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700742 }
743}
744
745void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800746 // Grab the latest ServerStatistics message. This will always have the
747 // oppertunity to be >= to the current time, so it will always represent any
748 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700749 WriteMissingTimestamps();
750
751 // Write each channel to disk, one at a time.
752 for (FetcherStruct &f : fetchers_) {
753 while (true) {
754 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700755 const auto start = event_loop_->monotonic_now();
756 const bool got_new = f.fetcher->FetchNext();
757 const auto end = event_loop_->monotonic_now();
758 RecordFetchResult(start, end, got_new, &f);
759 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700760 VLOG(2) << "No new data on "
761 << configuration::CleanedChannelToString(
762 f.fetcher->channel());
763 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700764 }
Brian Silvermancb805822020-10-06 17:43:35 -0700765 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700766 }
767
Austin Schuh2f8fd752020-09-01 22:38:28 -0700768 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700769 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700770 break;
771 }
Brian Silvermancb805822020-10-06 17:43:35 -0700772 if (f.writer != nullptr) {
773 // Write!
774 const auto start = event_loop_->monotonic_now();
775 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
776 max_header_size_);
777 fbb.ForceDefaults(true);
778
779 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
780 f.channel_index, f.log_type));
781 const auto end = event_loop_->monotonic_now();
782 RecordCreateMessageTime(start, end, &f);
783
784 VLOG(2) << "Writing data as node "
785 << FlatbufferToJson(event_loop_->node()) << " for channel "
786 << configuration::CleanedChannelToString(f.fetcher->channel())
787 << " to " << f.writer->filename() << " data "
788 << FlatbufferToJson(
789 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
790 fbb.GetBufferPointer()));
791
792 max_header_size_ = std::max(max_header_size_,
793 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800794 CHECK(node_state_[f.data_node_index].header_valid)
795 << ": Can't write data before the header on channel "
796 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700797 f.writer->QueueSizedFlatbuffer(&fbb);
798 }
799
800 if (f.timestamp_writer != nullptr) {
801 // And now handle timestamps.
802 const auto start = event_loop_->monotonic_now();
803 flatbuffers::FlatBufferBuilder fbb;
804 fbb.ForceDefaults(true);
805
806 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
807 f.channel_index,
808 LogType::kLogDeliveryTimeOnly));
809 const auto end = event_loop_->monotonic_now();
810 RecordCreateMessageTime(start, end, &f);
811
812 VLOG(2) << "Writing timestamps as node "
813 << FlatbufferToJson(event_loop_->node()) << " for channel "
814 << configuration::CleanedChannelToString(f.fetcher->channel())
815 << " to " << f.timestamp_writer->filename() << " timestamp "
816 << FlatbufferToJson(
817 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
818 fbb.GetBufferPointer()));
819
Austin Schuh315b96b2020-12-11 21:21:12 -0800820 CHECK(node_state_[f.timestamp_node_index].header_valid)
821 << ": Can't write data before the header on channel "
822 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700823 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
824 }
825
826 if (f.contents_writer != nullptr) {
827 const auto start = event_loop_->monotonic_now();
828 // And now handle the special message contents channel. Copy the
829 // message into a FlatBufferBuilder and save it to disk.
830 // TODO(austin): We can be more efficient here when we start to
831 // care...
832 flatbuffers::FlatBufferBuilder fbb;
833 fbb.ForceDefaults(true);
834
Austin Schuh0de30f32020-12-06 12:44:28 -0800835 const RemoteMessage *msg =
836 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700837
Austin Schuh315b96b2020-12-11 21:21:12 -0800838 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
839 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
840 node_state_[f.contents_node_index].source_node_boot_uuid !=
841 msg->boot_uuid()->string_view()) {
842 node_state_[f.contents_node_index].SetBootUUID(
843 msg->boot_uuid()->string_view());
844
845 MaybeWriteHeader(f.contents_node_index);
846 }
847
Brian Silvermancb805822020-10-06 17:43:35 -0700848 logger::MessageHeader::Builder message_header_builder(fbb);
849
850 // TODO(austin): This needs to check the channel_index and confirm
851 // that it should be logged before squirreling away the timestamp to
852 // disk. We don't want to log irrelevant timestamps.
853
854 // Note: this must match the same order as MessageBridgeServer and
855 // PackMessage. We want identical headers to have identical
856 // on-the-wire formats to make comparing them easier.
857
858 // Translate from the channel index that the event loop uses to the
859 // channel index in the log file.
860 message_header_builder.add_channel_index(
861 event_loop_to_logged_channel_index_[msg->channel_index()]);
862
863 message_header_builder.add_queue_index(msg->queue_index());
864 message_header_builder.add_monotonic_sent_time(
865 msg->monotonic_sent_time());
866 message_header_builder.add_realtime_sent_time(
867 msg->realtime_sent_time());
868
869 message_header_builder.add_monotonic_remote_time(
870 msg->monotonic_remote_time());
871 message_header_builder.add_realtime_remote_time(
872 msg->realtime_remote_time());
873 message_header_builder.add_remote_queue_index(
874 msg->remote_queue_index());
875
Austin Schuh969cd602021-01-03 00:09:45 -0800876 message_header_builder.add_monotonic_timestamp_time(
877 f.fetcher->context()
878 .monotonic_event_time.time_since_epoch()
879 .count());
880
Brian Silvermancb805822020-10-06 17:43:35 -0700881 fbb.FinishSizePrefixed(message_header_builder.Finish());
882 const auto end = event_loop_->monotonic_now();
883 RecordCreateMessageTime(start, end, &f);
884
Austin Schuh315b96b2020-12-11 21:21:12 -0800885 CHECK(node_state_[f.contents_node_index].header_valid)
886 << ": Can't write data before the header on channel "
887 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700888 f.contents_writer->QueueSizedFlatbuffer(&fbb);
889 }
890
891 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700892 }
893 }
894 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800895}
896
Brian Silverman1f345222020-09-24 21:14:48 -0700897void Logger::DoLogData(const monotonic_clock::time_point end_time) {
898 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800899 // max_out_of_order_duration. To do this, we need sync points. Every write
900 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800901
902 do {
903 // Move the sync point up by at most polling_period. This forces one sync
904 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700905 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
906
907 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800908
Austin Schuhe309d2a2019-11-29 13:25:21 -0800909 // If we missed cycles, we could be pretty far behind. Spin until we are
910 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700911 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800912}
913
Brian Silvermancb805822020-10-06 17:43:35 -0700914void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
915 aos::monotonic_clock::time_point end,
916 bool got_new, FetcherStruct *fetcher) {
917 const auto duration = end - start;
918 if (!got_new) {
919 ++total_nop_fetch_count_;
920 total_nop_fetch_time_ += duration;
921 return;
922 }
923 ++total_message_fetch_count_;
924 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
925 total_message_fetch_time_ += duration;
926 if (duration > max_message_fetch_time_) {
927 max_message_fetch_time_ = duration;
928 max_message_fetch_time_channel_ = fetcher->channel_index;
929 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
930 }
931}
932
933void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
934 aos::monotonic_clock::time_point end,
935 FetcherStruct *fetcher) {
936 const auto duration = end - start;
937 total_copy_time_ += duration;
938 ++total_copy_count_;
939 total_copy_bytes_ += fetcher->fetcher->context().size;
940 if (duration > max_copy_time_) {
941 max_copy_time_ = duration;
942 max_copy_time_channel_ = fetcher->channel_index;
943 max_copy_time_size_ = fetcher->fetcher->context().size;
944 }
945}
946
Austin Schuh11d43732020-09-21 17:28:30 -0700947std::vector<std::vector<std::string>> ToLogReaderVector(
948 const std::vector<LogFile> &log_files) {
949 std::vector<std::vector<std::string>> result;
950 for (const LogFile &log_file : log_files) {
951 for (const LogParts &log_parts : log_file.parts) {
952 std::vector<std::string> parts;
953 for (const std::string &part : log_parts.parts) {
954 parts.emplace_back(part);
955 }
956 result.emplace_back(std::move(parts));
957 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700958 }
959 return result;
960}
961
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800962LogReader::LogReader(std::string_view filename,
963 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800964 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800965
Austin Schuh287d43d2020-12-04 20:19:33 -0800966LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800967 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800968 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800969 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800970 CHECK_GT(log_files_.size(), 0u);
971 {
972 // Validate that we have the same config everwhere. This will be true if
973 // all the parts were sorted together and the configs match.
974 const Configuration *config = nullptr;
975 for (const LogFile &log_file : log_files) {
976 if (config == nullptr) {
977 config = log_file.config.get();
978 } else {
979 CHECK_EQ(config, log_file.config.get());
980 }
981 }
982 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800983
Austin Schuh6331ef92020-01-07 18:28:09 -0800984 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800985
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700986 // Remap all existing remote timestamp channels. They will be recreated, and
987 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700988 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700989 std::vector<const Node *> timestamp_logger_nodes =
990 configuration::TimestampNodes(logged_configuration(), node);
991 for (const Node *remote_node : timestamp_logger_nodes) {
992 const std::string channel = absl::StrCat(
993 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800994 // See if the log file is an old log with MessageHeader channels in it, or
995 // a newer log with RemoteMessage. If we find an older log, rename the
996 // type too along with the name.
997 if (HasChannel<MessageHeader>(channel, node)) {
998 CHECK(!HasChannel<RemoteMessage>(channel, node))
999 << ": Can't have both a MessageHeader and RemoteMessage remote "
1000 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001001 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
1002 // careful about updating the config, but there are fewer and fewer logs
1003 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -08001004 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
1005 "aos.message_bridge.RemoteMessage");
1006 } else {
1007 CHECK(HasChannel<RemoteMessage>(channel, node))
1008 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
1009 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
1010 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001011 // Only bother to remap if there's something on the channel. We can
1012 // tell if the channel was marked NOT_LOGGED or not. This makes the
1013 // config not change un-necesarily when we replay a log with NOT_LOGGED
1014 // messages.
1015 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
1016 RemapLoggedChannel<RemoteMessage>(channel, node);
1017 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001018 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001019 }
1020 }
1021
Austin Schuh6aa77be2020-02-22 21:06:40 -08001022 if (replay_configuration) {
1023 CHECK_EQ(configuration::MultiNode(configuration()),
1024 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001025 << ": Log file and replay config need to both be multi or single "
1026 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -08001027 }
1028
Austin Schuh6f3babe2020-01-26 20:34:50 -08001029 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001030 states_.emplace_back(std::make_unique<State>(
1031 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -08001032 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001033 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -07001034 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -08001035 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -07001036 << ": Log file and replay config need to have matching nodes "
1037 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001038 for (const Node *node : *logged_configuration()->nodes()) {
1039 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001040 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
1041 << " in logged config that is not present in the replay "
1042 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001043 }
1044 }
Austin Schuh6aa77be2020-02-22 21:06:40 -08001045 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001046 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001047 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001048}
1049
Austin Schuh6aa77be2020-02-22 21:06:40 -08001050LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -07001051 if (event_loop_factory_unique_ptr_) {
1052 Deregister();
1053 } else if (event_loop_factory_ != nullptr) {
1054 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
1055 "is destroyed";
1056 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001057 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1058 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001059 if (remapped_configuration_buffer_) {
1060 remapped_configuration_buffer_->Wipe();
1061 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001062}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001063
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001064const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001065 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001066}
1067
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001068const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001069 return remapped_configuration_;
1070}
1071
Austin Schuh6f3babe2020-01-26 20:34:50 -08001072std::vector<const Node *> LogReader::Nodes() const {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001073 // Because the Node pointer will only be valid if it actually points to
1074 // memory owned by remapped_configuration_, we need to wait for the
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001075 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001076 //
1077 // Also, note, that when ever a map is changed, the nodes in here are
1078 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001079 CHECK(remapped_configuration_ != nullptr)
1080 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -08001081 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001082}
Austin Schuh15649d62019-12-28 16:36:38 -08001083
Austin Schuh11d43732020-09-21 17:28:30 -07001084monotonic_clock::time_point LogReader::monotonic_start_time(
1085 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001086 State *state =
1087 states_[configuration::GetNodeIndex(configuration(), node)].get();
1088 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1089
Austin Schuh858c9f32020-08-31 16:56:12 -07001090 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001091}
1092
Austin Schuh11d43732020-09-21 17:28:30 -07001093realtime_clock::time_point LogReader::realtime_start_time(
1094 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001095 State *state =
1096 states_[configuration::GetNodeIndex(configuration(), node)].get();
1097 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1098
Austin Schuh858c9f32020-08-31 16:56:12 -07001099 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001100}
1101
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001102void LogReader::Register() {
1103 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001104 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001105 Register(event_loop_factory_unique_ptr_.get());
1106}
1107
Austin Schuh92547522019-12-28 14:33:43 -08001108void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001109 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001110 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001111 filters_ =
1112 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuh87dd3832021-01-01 23:07:31 -08001113 event_loop_factory_, logged_configuration(),
1114 FLAGS_skip_order_validation);
Austin Schuh92547522019-12-28 14:33:43 -08001115
Brian Silvermand90905f2020-09-23 14:42:56 -07001116 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001117 const size_t node_index =
1118 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001119 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1120 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001121
1122 // Confirm that all the parts are from the same boot if there are enough
1123 // parts to not be from the same boot.
1124 if (filtered_parts.size() > 1u) {
1125 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1126 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1127 filtered_parts[0].source_boot_uuid)
1128 << ": Found parts from different boots "
1129 << LogFileVectorToString(log_files_);
1130 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001131 if (!filtered_parts[0].source_boot_uuid.empty()) {
1132 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
1133 filtered_parts[0].source_boot_uuid);
1134 }
Austin Schuh315b96b2020-12-11 21:21:12 -08001135 }
1136
Austin Schuh287d43d2020-12-04 20:19:33 -08001137 states_[node_index] = std::make_unique<State>(
1138 filtered_parts.size() == 0u
1139 ? nullptr
1140 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001141 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001142 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001143 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001144
1145 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhcde938c2020-02-02 17:30:07 -08001146 }
Austin Schuh87dd3832021-01-01 23:07:31 -08001147 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001148
Austin Schuh287d43d2020-12-04 20:19:33 -08001149 for (const Node *node : configuration::GetNodes(configuration())) {
1150 const size_t node_index =
1151 configuration::GetNodeIndex(configuration(), node);
1152 State *state = states_[node_index].get();
1153 for (const Node *other_node : configuration::GetNodes(configuration())) {
1154 const size_t other_node_index =
1155 configuration::GetNodeIndex(configuration(), other_node);
1156 State *other_state = states_[other_node_index].get();
1157 if (other_state != state) {
1158 state->AddPeer(other_state);
1159 }
1160 }
1161 }
1162
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001163 // Register after making all the State objects so we can build references
1164 // between them.
1165 for (const Node *node : configuration::GetNodes(configuration())) {
1166 const size_t node_index =
1167 configuration::GetNodeIndex(configuration(), node);
1168 State *state = states_[node_index].get();
1169
1170 Register(state->event_loop());
1171 }
1172
James Kuszmaul46d82582020-05-09 19:50:09 -07001173 if (live_nodes_ == 0) {
1174 LOG(FATAL)
1175 << "Don't have logs from any of the nodes in the replay config--are "
1176 "you sure that the replay config matches the original config?";
1177 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001178
Austin Schuh87dd3832021-01-01 23:07:31 -08001179 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001180
Austin Schuh858c9f32020-08-31 16:56:12 -07001181 for (std::unique_ptr<State> &state : states_) {
1182 state->SeedSortedMessages();
1183 }
1184
Austin Schuh2f8fd752020-09-01 22:38:28 -07001185 // We want to start the log file at the last start time of the log files
1186 // from all the nodes. Compute how long each node's simulation needs to run
1187 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001188 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001189
Austin Schuh2f8fd752020-09-01 22:38:28 -07001190 // TODO(austin): We want an "OnStart" callback for each node rather than
1191 // running until the last node.
1192
Austin Schuh8bd96322020-02-13 21:18:22 -08001193 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001194 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1195 << MaybeNodeName(state->event_loop()->node()) << "now "
1196 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001197 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1198 continue;
1199 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001200 // And start computing the start time on the distributed clock now that
1201 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001202 start_time = std::max(
1203 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001204 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205
Austin Schuh87dd3832021-01-01 23:07:31 -08001206 // TODO(austin): If a node doesn't have a start time, we might not queue
1207 // enough. If this happens, we'll explode with a frozen error eventually.
1208
Austin Schuh2f8fd752020-09-01 22:38:28 -07001209 CHECK_GE(start_time, distributed_clock::epoch())
1210 << ": Hmm, we have a node starting before the start of time. Offset "
1211 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001212
Austin Schuh6f3babe2020-01-26 20:34:50 -08001213 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1214 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001215 // nodes, and also replayed on the other nodes. This may not satisfy all
1216 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001217 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1218 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1219 const Channel *channel = logged_configuration()->channels()->Get(i);
1220 const Node *node = configuration::GetNode(
1221 configuration(), channel->source_node()->string_view());
1222
Austin Schuh8bd96322020-02-13 21:18:22 -08001223 State *state =
1224 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225
1226 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001227 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001228
1229 event_loop_factory_->DisableForwarding(remapped_channel);
1230 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001231
1232 // If we are replaying a log, we don't want a bunch of redundant messages
1233 // from both the real message bridge and simulated message bridge.
1234 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001235 }
1236
Austin Schuhcde938c2020-02-02 17:30:07 -08001237 // While we are starting the system up, we might be relying on matching data
1238 // to timestamps on log files where the timestamp log file starts before the
1239 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -08001240 {
1241 const bool prior_ignore_missing_data = ignore_missing_data_;
1242 ignore_missing_data_ = true;
1243 VLOG(1) << "Running until " << start_time << " in Register";
1244 event_loop_factory_->RunFor(start_time.time_since_epoch());
1245 VLOG(1) << "At start time";
1246 // Now that we are running for real, missing data means that the log file is
1247 // corrupted or went wrong.
1248 ignore_missing_data_ = prior_ignore_missing_data;
1249 }
Austin Schuh92547522019-12-28 14:33:43 -08001250
Austin Schuh8bd96322020-02-13 21:18:22 -08001251 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001252 // Make the RT clock be correct before handing it to the user.
1253 if (state->realtime_start_time() != realtime_clock::min_time) {
1254 state->SetRealtimeOffset(state->monotonic_start_time(),
1255 state->realtime_start_time());
1256 }
1257 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1258 << MaybeNodeName(state->event_loop()->node()) << "now "
1259 << state->monotonic_now();
1260 }
1261
1262 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001263 filters_->Start(event_loop_factory);
Austin Schuhaceeb712021-01-06 22:50:00 -08001264 std::fstream s("/tmp/timestamp_noncausal_starttime.csv", s.trunc | s.out);
1265 CHECK(s.is_open());
1266 for (std::unique_ptr<State> &state : states_) {
1267 s << state->event_loop()->node()->name()->string_view() << ", "
1268 << std::setprecision(12) << std::fixed
1269 << chrono::duration<double>(state->monotonic_now().time_since_epoch())
1270 .count()
1271 << "\n";
1272 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001273 }
1274}
1275
Austin Schuh2f8fd752020-09-01 22:38:28 -07001276message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001277 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001278 if (filters_) {
1279 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001280 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001281 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001282}
1283
Austin Schuhe309d2a2019-11-29 13:25:21 -08001284void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001285 State *state =
1286 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1287 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001288
Austin Schuh858c9f32020-08-31 16:56:12 -07001289 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001290
Tyler Chatow67ddb032020-01-12 14:30:04 -08001291 // We don't run timing reports when trying to print out logged data, because
1292 // otherwise we would end up printing out the timing reports themselves...
1293 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001294 event_loop->SkipTimingReport();
1295 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001296
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001297 for (size_t logged_channel_index = 0;
1298 logged_channel_index < logged_configuration()->channels()->size();
1299 ++logged_channel_index) {
1300 const Channel *channel = RemapChannel(
1301 event_loop,
1302 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001303
Austin Schuh532656d2021-01-11 10:17:18 -08001304 if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1305 continue;
1306 }
1307
Austin Schuh2f8fd752020-09-01 22:38:28 -07001308 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -08001309 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001310
1311 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001312
1313 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1314 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001315 // We've got a message which is being forwarded to this node.
1316 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001317 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001318 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001319
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001320 // Delivery timestamps are supposed to be logged back on the source node.
1321 // Configure remote timestamps to be sent.
1322 const bool delivery_time_is_logged =
1323 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1324 channel, event_loop->node(), source_node);
1325
1326 source_state =
1327 states_[configuration::GetNodeIndex(configuration(), source_node)]
1328 .get();
1329
1330 if (delivery_time_is_logged) {
1331 remote_timestamp_sender =
1332 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001333 }
1334 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001335
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001336 state->SetChannel(
1337 logged_channel_index,
1338 configuration::ChannelIndex(event_loop->configuration(), channel),
1339 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1340 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001341 }
1342
Austin Schuh6aa77be2020-02-22 21:06:40 -08001343 // If we didn't find any log files with data in them, we won't ever get a
1344 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001345 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001346 return;
1347 }
1348
Austin Schuh858c9f32020-08-31 16:56:12 -07001349 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001350 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1351 << "at " << state->event_loop()->context().monotonic_event_time
1352 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001353 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001354 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001355 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001356 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001357 event_loop_factory_->Exit();
1358 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001359 return;
1360 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361
Austin Schuhdda74ec2021-01-03 19:30:37 -08001362 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -08001363
Austin Schuhe309d2a2019-11-29 13:25:21 -08001364 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001365 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001366 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001367 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001368 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1369 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001370 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001371 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001372 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001373 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001374 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001375 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001376 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001377 << "): " << FlatbufferToJson(state->event_loop()->node())
1378 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001379 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001380 << state->DebugString();
1381 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001382
Austin Schuh287d43d2020-12-04 20:19:33 -08001383 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001384 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001385 event_loop_factory_ != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001386 if (timestamped_message.data.span().size() != 0u) {
1387 if (timestamped_message.monotonic_remote_time !=
1388 monotonic_clock::min_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001389 // Confirm that the message was sent on the sending node before the
1390 // destination node (this node). As a proxy, do this by making sure
1391 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001392 //
1393 // TODO(austin): <= means that the cause message (which we know) could
1394 // happen after the effect even though we know they are at the same
1395 // time. I doubt anyone will notice for a bit, but we should really
1396 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001397 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001398 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -08001399 timestamped_message.monotonic_remote_time,
1400 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001401 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001402 << state->remote_node(timestamped_message.channel_index)
1403 ->name()
1404 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001405 << " while trying to send a message on "
1406 << configuration::CleanedChannelToString(
1407 logged_configuration()->channels()->Get(
1408 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001409 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -08001410 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -08001411 state->monotonic_remote_now(
1412 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001413 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001414 << "Check failed: timestamped_message.monotonic_remote_time < "
1415 "state->monotonic_remote_now(timestamped_message.channel_"
1416 "index) ("
1417 << timestamped_message.monotonic_remote_time << " vs. "
1418 << state->monotonic_remote_now(
1419 timestamped_message.channel_index)
1420 << ") " << state->event_loop()->node()->name()->string_view()
1421 << " to "
1422 << state->remote_node(timestamped_message.channel_index)
1423 ->name()
1424 ->string_view()
1425 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001426 << " ("
1427 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001428 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001429 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001430 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001431 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001432 timestamped_message.channel_index,
1433 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001434 << ") " << state->DebugString();
1435 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001436 }
1437
Austin Schuh15649d62019-12-28 16:36:38 -08001438 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001439 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1440 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001441
Austin Schuh2f8fd752020-09-01 22:38:28 -07001442 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001443 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001444 // TODO(austin): std::move channel_data in and make that efficient in
1445 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001446 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -08001447 } else if (!ignore_missing_data_ &&
1448 !FLAGS_skip_missing_forwarding_entries) {
1449 // We've found a timestamp without data. This likely means that we are
1450 // at the end of the log file. Record it and CHECK that in the rest of
1451 // the log file, we don't find any more data on that channel. Not all
1452 // channels will end at the same point in time since they can be in
1453 // different files.
1454 VLOG(1) << "Found the last message on channel "
1455 << timestamped_message.channel_index;
1456
1457 // Vector storing if we've seen a nullptr message or not per channel.
1458 std::vector<bool> last_message;
1459 last_message.resize(logged_configuration()->channels()->size(), false);
1460
1461 last_message[timestamped_message.channel_index] = true;
1462
1463 // Now that we found the end of one channel, artificially stop the
1464 // rest. It is confusing when part of your data gets replayed but not
1465 // all.
Austin Schuh858c9f32020-08-31 16:56:12 -07001466 while (state->OldestMessageTime() != monotonic_clock::max_time) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001467 TimestampedMessage next = state->PopOldest();
1468 // Make sure that once we have seen the last message on a channel,
1469 // data doesn't start back up again. If the user wants to play
1470 // through events like this, they can set
1471 // --skip_missing_forwarding_entries or ignore_missing_data_.
1472 CHECK_LT(next.channel_index, last_message.size());
1473 if (next.data.span().size() == 0u) {
1474 last_message[next.channel_index] = true;
1475 } else {
1476 if (last_message[next.channel_index]) {
1477 LOG(FATAL)
1478 << "Found missing data in the middle of the log file on "
1479 "channel "
1480 << next.channel_index << " Last "
1481 << last_message[next.channel_index] << state->DebugString();
1482 }
1483 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001484 }
Austin Schuh92547522019-12-28 14:33:43 -08001485 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001486 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001487 LOG(WARNING)
1488 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001489 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001490 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001491 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001492 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001493 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001494 }
1495
Austin Schuh858c9f32020-08-31 16:56:12 -07001496 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001497 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001498 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1499 << "wakeup for " << next_time << "("
1500 << state->ToDistributedClock(next_time)
1501 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001502 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001503 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001504 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1505 << "No next message, scheduling shutdown";
1506 // Set a timer up immediately after now to die. If we don't do this,
1507 // then the senders waiting on the message we just read will never get
1508 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001509 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001510 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1511 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001512 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001513 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001514
Austin Schuh2f8fd752020-09-01 22:38:28 -07001515 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1516 << state->event_loop()->context().monotonic_event_time << " now "
1517 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001518 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001519
Austin Schuh6f3babe2020-01-26 20:34:50 -08001520 ++live_nodes_;
1521
Austin Schuh858c9f32020-08-31 16:56:12 -07001522 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1523 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001524 }
1525}
1526
1527void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001528 // Make sure that things get destroyed in the correct order, rather than
1529 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001530 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001531 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001532 }
Austin Schuh92547522019-12-28 14:33:43 -08001533
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001534 event_loop_factory_unique_ptr_.reset();
1535 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001536}
1537
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001538void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001539 std::string_view add_prefix,
1540 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001541 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1542 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1543 if (channel->name()->str() == name &&
1544 channel->type()->string_view() == type) {
1545 CHECK_EQ(0u, remapped_channels_.count(ii))
1546 << "Already remapped channel "
1547 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001548 RemappedChannel remapped_channel;
1549 remapped_channel.remapped_name =
1550 std::string(add_prefix) + std::string(name);
1551 remapped_channel.new_type = new_type;
1552 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001553 VLOG(1) << "Remapping channel "
1554 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001555 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001556 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001557 return;
1558 }
1559 }
1560 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1561 << type;
1562}
1563
Austin Schuh01b4c352020-09-21 23:09:39 -07001564void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1565 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001566 std::string_view add_prefix,
1567 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001568 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1569 const Channel *remapped_channel =
1570 configuration::GetChannel(logged_configuration(), name, type, "", node);
1571 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1572 << "\", \"type\": \"" << type << "\"}";
1573 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1574 << "\"}";
1575 VLOG(1) << "Remapped "
1576 << aos::configuration::StrippedChannelToString(remapped_channel);
1577
1578 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1579 // we want it to degrade if the heuristics fail to just work.
1580 //
1581 // The easiest way to do this is going to be incredibly specific and verbose.
1582 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1583 // /original/0/spray. Then, create a map from /original/spray to
1584 // /original/0/spray for just the type we were asked for.
1585 if (name != remapped_channel->name()->string_view()) {
1586 MapT new_map;
1587 new_map.match = std::make_unique<ChannelT>();
1588 new_map.match->name = absl::StrCat(add_prefix, name);
1589 new_map.match->type = type;
1590 if (node != nullptr) {
1591 new_map.match->source_node = node->name()->str();
1592 }
1593 new_map.rename = std::make_unique<ChannelT>();
1594 new_map.rename->name =
1595 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1596 maps_.emplace_back(std::move(new_map));
1597 }
1598
1599 const size_t channel_index =
1600 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1601 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1602 << "Already remapped channel "
1603 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001604
1605 RemappedChannel remapped_channel_struct;
1606 remapped_channel_struct.remapped_name =
1607 std::string(add_prefix) +
1608 std::string(remapped_channel->name()->string_view());
1609 remapped_channel_struct.new_type = new_type;
1610 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001611 MakeRemappedConfig();
1612}
1613
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001614void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001615 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001616 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001617 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001618 << ": Can't change the mapping after the events are scheduled.";
1619 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001620 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001621
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001622 // If no remapping occurred and we are using the original config, then there
1623 // is nothing interesting to do here.
1624 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001625 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001626 return;
1627 }
1628 // Config to copy Channel definitions from. Use the specified
1629 // replay_configuration_ if it has been provided.
1630 const Configuration *const base_config = replay_configuration_ == nullptr
1631 ? logged_configuration()
1632 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001633
1634 // Create a config with all the channels, but un-sorted/merged. Collect up
1635 // the schemas while we do this. Call MergeConfiguration to sort everything,
1636 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001637
1638 // This is the builder that we use for the config containing all the new
1639 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001640 flatbuffers::FlatBufferBuilder fbb;
1641 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001642 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001643
1644 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1645 << ": Merging logic needs to be updated when the number of channel "
1646 "fields changes.";
1647
1648 // List of schemas.
1649 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1650 // Make sure our new RemoteMessage schema is in there for old logs without it.
1651 schema_map.insert(std::make_pair(
1652 RemoteMessage::GetFullyQualifiedName(),
1653 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1654 message_bridge::RemoteMessageSchema()))));
1655
1656 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001657 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001658 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001659 base_config, logged_configuration()->channels()->Get(pair.first), "",
1660 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001661 channel_offsets.emplace_back(
1662 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001663 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001664
Austin Schuh0de30f32020-12-06 12:44:28 -08001665 // Now reconstruct the original channels, translating types as needed
1666 for (const Channel *c : *base_config->channels()) {
1667 // Search for a mapping channel.
1668 std::string_view new_type = "";
1669 for (auto &pair : remapped_channels_) {
1670 const Channel *const remapped_channel =
1671 logged_configuration()->channels()->Get(pair.first);
1672 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1673 remapped_channel->type()->string_view() == c->type()->string_view()) {
1674 new_type = pair.second.new_type;
1675 break;
1676 }
1677 }
1678
1679 // Copy everything over.
1680 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1681
1682 // Add the schema if it doesn't exist.
1683 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1684 CHECK(c->has_schema());
1685 schema_map.insert(std::make_pair(c->type()->string_view(),
1686 RecursiveCopyFlatBuffer(c->schema())));
1687 }
1688 }
1689
1690 // The MergeConfiguration API takes a vector, not a map. Convert.
1691 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1692 while (!schema_map.empty()) {
1693 schemas.emplace_back(std::move(schema_map.begin()->second));
1694 schema_map.erase(schema_map.begin());
1695 }
1696
1697 // Create the Configuration containing the new channels that we want to add.
1698 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1699 channels_offset =
1700 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1701
1702 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001703 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001704 if (base_config->maps()) {
1705 for (const Map *map : *base_config->maps()) {
1706 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1707 }
1708 }
1709
1710 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001711 for (const MapT &map : maps_) {
1712 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001713 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001714 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001715 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001716 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001717 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001718 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1719 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001720 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001721 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001722 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001723 match_builder.add_name(match_name_offset);
1724 match_builder.add_type(match_type_offset);
1725 if (!map.match->source_node.empty()) {
1726 match_builder.add_source_node(match_source_node_offset);
1727 }
1728 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1729
Austin Schuh0de30f32020-12-06 12:44:28 -08001730 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001731 rename_builder.add_name(rename_name_offset);
1732 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1733
Austin Schuh0de30f32020-12-06 12:44:28 -08001734 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001735 map_builder.add_match(match_offset);
1736 map_builder.add_rename(rename_offset);
1737 map_offsets.emplace_back(map_builder.Finish());
1738 }
1739
Austin Schuh0de30f32020-12-06 12:44:28 -08001740 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1741 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001742
Austin Schuh0de30f32020-12-06 12:44:28 -08001743 // And copy everything else over.
1744 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1745 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1746
1747 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1748 applications_offset =
1749 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1750
1751 // Now insert everything else in unmodified.
1752 ConfigurationBuilder configuration_builder(fbb);
1753 if (!channels_offset.IsNull()) {
1754 configuration_builder.add_channels(channels_offset);
1755 }
1756 if (!maps_offsets.IsNull()) {
1757 configuration_builder.add_maps(maps_offsets);
1758 }
1759 if (!nodes_offset.IsNull()) {
1760 configuration_builder.add_nodes(nodes_offset);
1761 }
1762 if (!applications_offset.IsNull()) {
1763 configuration_builder.add_applications(applications_offset);
1764 }
1765
1766 if (base_config->has_channel_storage_duration()) {
1767 configuration_builder.add_channel_storage_duration(
1768 base_config->channel_storage_duration());
1769 }
1770
1771 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1772 << ": Merging logic needs to be updated when the number of configuration "
1773 "fields changes.";
1774
1775 fbb.Finish(configuration_builder.Finish());
1776
1777 // Clean it up and return it! By using MergeConfiguration here, we'll
1778 // actually get a deduplicated config for free too.
1779 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1780 configuration::MergeConfiguration(
1781 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1782
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001783 remapped_configuration_buffer_ =
1784 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001785 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001786
1787 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001788
1789 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001790}
1791
Austin Schuh6f3babe2020-01-26 20:34:50 -08001792const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1793 const Channel *channel) {
1794 std::string_view channel_name = channel->name()->string_view();
1795 std::string_view channel_type = channel->type()->string_view();
1796 const int channel_index =
1797 configuration::ChannelIndex(logged_configuration(), channel);
1798 // If the channel is remapped, find the correct channel name to use.
1799 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001800 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001801 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001802 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001803 }
1804
Austin Schuhee711052020-08-24 16:06:09 -07001805 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001806 const Channel *remapped_channel = configuration::GetChannel(
1807 event_loop->configuration(), channel_name, channel_type,
1808 event_loop->name(), event_loop->node());
1809
1810 CHECK(remapped_channel != nullptr)
1811 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1812 << channel_type << "\"} because it is not in the provided configuration.";
1813
1814 return remapped_channel;
1815}
1816
Austin Schuh287d43d2020-12-04 20:19:33 -08001817LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1818 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1819
1820void LogReader::State::AddPeer(State *peer) {
1821 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1822 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1823 }
1824}
Austin Schuh858c9f32020-08-31 16:56:12 -07001825
1826EventLoop *LogReader::State::SetNodeEventLoopFactory(
1827 NodeEventLoopFactory *node_event_loop_factory) {
1828 node_event_loop_factory_ = node_event_loop_factory;
1829 event_loop_unique_ptr_ =
1830 node_event_loop_factory_->MakeEventLoop("log_reader");
1831 return event_loop_unique_ptr_.get();
1832}
1833
1834void LogReader::State::SetChannelCount(size_t count) {
1835 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001836 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001837 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001838 channel_source_state_.resize(count);
1839 factory_channel_index_.resize(count);
1840 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001841}
1842
1843void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001844 size_t logged_channel_index, size_t factory_channel_index,
1845 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001846 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001847 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001848 channels_[logged_channel_index] = std::move(sender);
1849 filters_[logged_channel_index] = filter;
1850 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1851
1852 if (source_state) {
1853 channel_source_state_[logged_channel_index] = source_state;
1854
1855 if (remote_timestamp_sender != nullptr) {
1856 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001857 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001858 }
1859 }
1860
1861 factory_channel_index_[logged_channel_index] = factory_channel_index;
1862}
1863
Austin Schuh287d43d2020-12-04 20:19:33 -08001864bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1865 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001866 uint32_t remote_queue_index = 0xffffffff;
1867
Austin Schuh287d43d2020-12-04 20:19:33 -08001868 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001869 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001870 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1871 ->queue_index_map_[timestamped_message.channel_index]
1872 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001873
Austin Schuh9942bae2021-01-07 22:06:44 -08001874 struct SentTimestamp {
1875 monotonic_clock::time_point monotonic_event_time;
1876 uint32_t queue_index;
1877 } search;
1878
Austin Schuh287d43d2020-12-04 20:19:33 -08001879 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001880 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001881
1882 // Find the sent time if available.
1883 auto element = std::lower_bound(
1884 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001885 [](ContiguousSentTimestamp a, SentTimestamp b) {
1886 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001887 return true;
1888 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001889 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001890 return false;
1891 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001892
1893 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001894 return true;
1895 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001896 if (a.starting_queue_index >= b.queue_index) {
1897 return false;
1898 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001899
Austin Schuh9942bae2021-01-07 22:06:44 -08001900 // If it isn't clearly below or above, it is below. Since we return
1901 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001902 return false;
1903 });
1904
1905 // TODO(austin): Be a bit more principled here, but we will want to do that
1906 // after the logger rewrite. We hit this when one node finishes, but the
1907 // other node isn't done yet. So there is no send time, but there is a
1908 // receive time.
1909 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001910 CHECK_GE(timestamped_message.monotonic_remote_time,
1911 element->starting_monotonic_event_time);
1912 CHECK_LE(timestamped_message.monotonic_remote_time,
1913 element->ending_monotonic_event_time);
1914 CHECK_GE(timestamped_message.remote_queue_index,
1915 element->starting_queue_index);
1916 CHECK_LE(timestamped_message.remote_queue_index,
1917 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001918
Austin Schuh9942bae2021-01-07 22:06:44 -08001919 remote_queue_index = timestamped_message.remote_queue_index +
1920 element->actual_queue_index -
1921 element->starting_queue_index;
1922 } else {
1923 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001924 }
1925 }
1926
1927 // Send! Use the replayed queue index here instead of the logged queue index
1928 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001929 const bool sent = sender->Send(
1930 timestamped_message.data.message().data()->Data(),
1931 timestamped_message.data.message().data()->size(),
1932 timestamped_message.monotonic_remote_time,
1933 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001934 if (!sent) return false;
1935
Austin Schuh287d43d2020-12-04 20:19:33 -08001936 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001937 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1938 // Nothing here, start a range with 0 length.
1939 ContiguousSentTimestamp timestamp;
1940 timestamp.starting_monotonic_event_time =
1941 timestamp.ending_monotonic_event_time =
1942 timestamped_message.monotonic_event_time;
1943 timestamp.starting_queue_index = timestamp.ending_queue_index =
1944 timestamped_message.queue_index;
1945 timestamp.actual_queue_index = sender->sent_queue_index();
1946 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1947 timestamp);
1948 } else {
1949 // We've got something. See if the next timestamp is still contiguous. If
1950 // so, grow it.
1951 ContiguousSentTimestamp *back =
1952 &queue_index_map_[timestamped_message.channel_index]->back();
1953 if ((back->starting_queue_index - back->actual_queue_index) ==
1954 (timestamped_message.queue_index - sender->sent_queue_index())) {
1955 back->ending_queue_index = timestamped_message.queue_index;
1956 back->ending_monotonic_event_time =
1957 timestamped_message.monotonic_event_time;
1958 } else {
1959 // Otherwise, make a new one.
1960 ContiguousSentTimestamp timestamp;
1961 timestamp.starting_monotonic_event_time =
1962 timestamp.ending_monotonic_event_time =
1963 timestamped_message.monotonic_event_time;
1964 timestamp.starting_queue_index = timestamp.ending_queue_index =
1965 timestamped_message.queue_index;
1966 timestamp.actual_queue_index = sender->sent_queue_index();
1967 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1968 timestamp);
1969 }
1970 }
1971
1972 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1973 // queue index diverge a couple of elements, which would be a very small
1974 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001975 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1976 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001977 flatbuffers::FlatBufferBuilder fbb;
1978 fbb.ForceDefaults(true);
Austin Schuh315b96b2020-12-11 21:21:12 -08001979 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
Austin Schuh969cd602021-01-03 00:09:45 -08001980 fbb.CreateString(event_loop_->boot_uuid().string_view());
Austin Schuh315b96b2020-12-11 21:21:12 -08001981
Austin Schuh969cd602021-01-03 00:09:45 -08001982 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001983
1984 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001985 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001986
1987 // Swap the remote and sent metrics. They are from the sender's
1988 // perspective, not the receiver's perspective.
1989 message_header_builder.add_monotonic_sent_time(
1990 sender->monotonic_sent_time().time_since_epoch().count());
1991 message_header_builder.add_realtime_sent_time(
1992 sender->realtime_sent_time().time_since_epoch().count());
1993 message_header_builder.add_queue_index(sender->sent_queue_index());
1994
1995 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001996 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001997 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001998 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001999
2000 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08002001 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002002
Austin Schuh969cd602021-01-03 00:09:45 -08002003 fbb.Finish(message_header_builder.Finish());
2004
2005 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
2006 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
2007 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002008 }
2009
2010 return true;
2011}
2012
Austin Schuh969cd602021-01-03 00:09:45 -08002013LogReader::RemoteMessageSender::RemoteMessageSender(
2014 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2015 : event_loop_(event_loop),
2016 sender_(std::move(sender)),
2017 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2018
2019void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2020 if (remote_timestamps_.empty()) {
2021 CHECK_NOTNULL(timer_);
2022 timer_->Disable();
2023 scheduled_time_ = monotonic_clock::min_time;
2024 return;
2025 }
2026
2027 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2028 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002029 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002030 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
2031 }
2032}
2033
2034void LogReader::RemoteMessageSender::Send(
2035 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
2036 monotonic_clock::time_point monotonic_timestamp_time) {
2037 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
2038 // resend the timestamp at the correct time, or we don't and can send it
2039 // immediately.
2040 if (monotonic_timestamp_time == monotonic_clock::min_time) {
2041 CHECK(remote_timestamps_.empty())
2042 << ": Unsupported mix of timestamps and no timestamps.";
2043 sender_.Send(std::move(remote_message));
2044 } else {
2045 remote_timestamps_.emplace_back(std::move(remote_message),
2046 monotonic_timestamp_time);
2047 ScheduleTimestamp();
2048 }
2049}
2050
2051void LogReader::RemoteMessageSender::SendTimestamp() {
2052 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_);
2053 CHECK(!remote_timestamps_.empty());
2054
2055 // Send out all timestamps at the currently scheduled time.
2056 while (remote_timestamps_.front().monotonic_timestamp_time ==
2057 scheduled_time_) {
2058 sender_.Send(std::move(remote_timestamps_.front().remote_message));
2059 remote_timestamps_.pop_front();
2060 if (remote_timestamps_.empty()) {
2061 break;
2062 }
2063 }
2064 scheduled_time_ = monotonic_clock::min_time;
2065
2066 ScheduleTimestamp();
2067}
2068
2069LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002070 const Node *delivered_node) {
2071 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2072
2073 if (sender == remote_timestamp_senders_map_.end()) {
Austin Schuh969cd602021-01-03 00:09:45 -08002074 sender =
2075 remote_timestamp_senders_map_
2076 .emplace(delivered_node,
2077 std::make_unique<RemoteMessageSender>(
2078 event_loop()->MakeSender<RemoteMessage>(absl::StrCat(
2079 "/aos/remote_timestamps/",
2080 delivered_node->name()->string_view())),
2081 event_loop()))
2082 .first;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002083 }
2084
Austin Schuh969cd602021-01-03 00:09:45 -08002085 return sender->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002086}
2087
Austin Schuhdda74ec2021-01-03 19:30:37 -08002088TimestampedMessage LogReader::State::PopOldest() {
Austin Schuh858c9f32020-08-31 16:56:12 -07002089 CHECK_GT(sorted_messages_.size(), 0u);
2090
Austin Schuh287d43d2020-12-04 20:19:33 -08002091 std::tuple<TimestampedMessage, message_bridge::NoncausalOffsetEstimator *>
Austin Schuh858c9f32020-08-31 16:56:12 -07002092 result = std::move(sorted_messages_.front());
Austin Schuh2f8fd752020-09-01 22:38:28 -07002093 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuh858c9f32020-08-31 16:56:12 -07002094 << std::get<0>(result).monotonic_event_time;
2095 sorted_messages_.pop_front();
2096 SeedSortedMessages();
2097
Austin Schuh287d43d2020-12-04 20:19:33 -08002098 if (std::get<1>(result) != nullptr) {
Austin Schuh816e5d62021-01-05 23:42:20 -08002099 std::get<1>(result)->Pop(event_loop_->node(),
2100 std::get<0>(result).monotonic_event_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002101 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002102 return std::move(std::get<0>(result));
Austin Schuh858c9f32020-08-31 16:56:12 -07002103}
2104
2105monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
2106 if (sorted_messages_.size() > 0) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002107 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
Austin Schuh858c9f32020-08-31 16:56:12 -07002108 << std::get<0>(sorted_messages_.front()).monotonic_event_time;
2109 return std::get<0>(sorted_messages_.front()).monotonic_event_time;
2110 }
2111
Austin Schuh287d43d2020-12-04 20:19:33 -08002112 TimestampedMessage *m =
2113 timestamp_mapper_ ? timestamp_mapper_->Front() : nullptr;
2114 if (m == nullptr) {
2115 return monotonic_clock::max_time;
2116 }
2117 return m->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002118}
2119
2120void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002121 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002122 const aos::monotonic_clock::time_point end_queue_time =
2123 (sorted_messages_.size() > 0
2124 ? std::get<0>(sorted_messages_.front()).monotonic_event_time
Austin Schuh287d43d2020-12-04 20:19:33 -08002125 : timestamp_mapper_->monotonic_start_time()) +
Austin Schuhf0688662020-12-19 15:37:45 -08002126 chrono::duration_cast<chrono::seconds>(
2127 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds));
Austin Schuh858c9f32020-08-31 16:56:12 -07002128
2129 while (true) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002130 TimestampedMessage *m = timestamp_mapper_->Front();
2131 if (m == nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07002132 return;
2133 }
2134 if (sorted_messages_.size() > 0) {
Austin Schuhf0688662020-12-19 15:37:45 -08002135 // Stop placing sorted messages on the list once we have
2136 // --time_estimation_buffer_seconds seconds queued up (but queue at least
2137 // until the log starts.
Austin Schuh858c9f32020-08-31 16:56:12 -07002138 if (end_queue_time <
2139 std::get<0>(sorted_messages_.back()).monotonic_event_time) {
2140 return;
2141 }
2142 }
2143
Austin Schuh2f8fd752020-09-01 22:38:28 -07002144 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
2145
Austin Schuh287d43d2020-12-04 20:19:33 -08002146 TimestampedMessage timestamped_message = std::move(*m);
2147 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002148
Austin Schuh2f8fd752020-09-01 22:38:28 -07002149 // Skip any messages without forwarding information.
Austin Schuh0de30f32020-12-06 12:44:28 -08002150 if (timestamped_message.monotonic_remote_time !=
2151 monotonic_clock::min_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07002152 // Got a forwarding timestamp!
Austin Schuh287d43d2020-12-04 20:19:33 -08002153 filter = filters_[timestamped_message.channel_index];
Austin Schuh2f8fd752020-09-01 22:38:28 -07002154
2155 CHECK(filter != nullptr);
2156
2157 // Call the correct method depending on if we are the forward or
2158 // reverse direction here.
2159 filter->Sample(event_loop_->node(),
Austin Schuh287d43d2020-12-04 20:19:33 -08002160 timestamped_message.monotonic_event_time,
2161 timestamped_message.monotonic_remote_time);
Austin Schuh816e5d62021-01-05 23:42:20 -08002162
2163 if (timestamped_message.monotonic_timestamp_time !=
2164 monotonic_clock::min_time) {
2165 // TODO(austin): This assumes that this timestamp is only logged on the
2166 // node which sent the data. That is correct for now, but should be
2167 // explicitly checked somewhere.
2168 filter->ReverseSample(event_loop_->node(),
2169 timestamped_message.monotonic_event_time,
2170 timestamped_message.monotonic_timestamp_time);
2171 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07002172 }
Austin Schuh287d43d2020-12-04 20:19:33 -08002173 sorted_messages_.emplace_back(std::move(timestamped_message), filter);
Austin Schuh858c9f32020-08-31 16:56:12 -07002174 }
2175}
2176
2177void LogReader::State::Deregister() {
2178 for (size_t i = 0; i < channels_.size(); ++i) {
2179 channels_[i].reset();
2180 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002181 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002182 event_loop_unique_ptr_.reset();
2183 event_loop_ = nullptr;
2184 timer_handler_ = nullptr;
2185 node_event_loop_factory_ = nullptr;
2186}
2187
Austin Schuhe309d2a2019-11-29 13:25:21 -08002188} // namespace logger
2189} // namespace aos