blob: acbbff2d78478c5a09a16276151a899344dfd316 [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>
Brian Silverman8ff74aa2021-02-05 16:37:15 -08008
Austin Schuhe309d2a2019-11-29 13:25:21 -08009#include <vector>
10
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 Schuhe309d2a2019-11-29 13:25:21 -080026
Austin Schuh15649d62019-12-28 16:36:38 -080027DEFINE_bool(skip_missing_forwarding_entries, false,
28 "If true, drop any forwarding entries with missing data. If "
29 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080030
Austin Schuh0ca1fd32020-12-18 22:53:05 -080031DECLARE_bool(timestamps_to_csv);
Austin Schuh8bd96322020-02-13 21:18:22 -080032
Austin Schuh2f8fd752020-09-01 22:38:28 -070033DEFINE_bool(skip_order_validation, false,
34 "If true, ignore any out of orderness in replay");
35
Austin Schuhf0688662020-12-19 15:37:45 -080036DEFINE_double(
37 time_estimation_buffer_seconds, 2.0,
38 "The time to buffer ahead in the log file to accurately reconstruct time.");
39
Austin Schuhe309d2a2019-11-29 13:25:21 -080040namespace aos {
41namespace logger {
Austin Schuh0afc4d12020-10-19 11:42:04 -070042namespace {
Austin Schuh8c399962020-12-25 21:51:45 -080043
Austin Schuh315b96b2020-12-11 21:21:12 -080044std::string LogFileVectorToString(std::vector<LogFile> log_files) {
45 std::stringstream ss;
Austin Schuh297d2352021-01-21 19:02:17 -080046 for (const auto &f : log_files) {
Austin Schuh315b96b2020-12-11 21:21:12 -080047 ss << f << "\n";
48 }
49 return ss.str();
50}
51
Austin Schuh0de30f32020-12-06 12:44:28 -080052// Copies the channel, removing the schema as we go. If new_name is provided,
53// it is used instead of the name inside the channel. If new_type is provided,
54// it is used instead of the type in the channel.
55flatbuffers::Offset<Channel> CopyChannel(const Channel *c,
56 std::string_view new_name,
57 std::string_view new_type,
58 flatbuffers::FlatBufferBuilder *fbb) {
59 flatbuffers::Offset<flatbuffers::String> name_offset =
60 fbb->CreateSharedString(new_name.empty() ? c->name()->string_view()
61 : new_name);
62 flatbuffers::Offset<flatbuffers::String> type_offset =
63 fbb->CreateSharedString(new_type.empty() ? c->type()->str() : new_type);
64 flatbuffers::Offset<flatbuffers::String> source_node_offset =
65 c->has_source_node() ? fbb->CreateSharedString(c->source_node()->str())
66 : 0;
67
68 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Connection>>>
69 destination_nodes_offset =
70 aos::RecursiveCopyVectorTable(c->destination_nodes(), fbb);
71
72 flatbuffers::Offset<
73 flatbuffers::Vector<flatbuffers::Offset<flatbuffers::String>>>
74 logger_nodes_offset = aos::CopyVectorSharedString(c->logger_nodes(), fbb);
75
76 Channel::Builder channel_builder(*fbb);
77 channel_builder.add_name(name_offset);
78 channel_builder.add_type(type_offset);
79 if (c->has_frequency()) {
80 channel_builder.add_frequency(c->frequency());
81 }
82 if (c->has_max_size()) {
83 channel_builder.add_max_size(c->max_size());
84 }
85 if (c->has_num_senders()) {
86 channel_builder.add_num_senders(c->num_senders());
87 }
88 if (c->has_num_watchers()) {
89 channel_builder.add_num_watchers(c->num_watchers());
90 }
91 if (!source_node_offset.IsNull()) {
92 channel_builder.add_source_node(source_node_offset);
93 }
94 if (!destination_nodes_offset.IsNull()) {
95 channel_builder.add_destination_nodes(destination_nodes_offset);
96 }
97 if (c->has_logger()) {
98 channel_builder.add_logger(c->logger());
99 }
100 if (!logger_nodes_offset.IsNull()) {
101 channel_builder.add_logger_nodes(logger_nodes_offset);
102 }
103 if (c->has_read_method()) {
104 channel_builder.add_read_method(c->read_method());
105 }
106 if (c->has_num_readers()) {
107 channel_builder.add_num_readers(c->num_readers());
108 }
109 return channel_builder.Finish();
110}
111
Austin Schuhe309d2a2019-11-29 13:25:21 -0800112namespace chrono = std::chrono;
Austin Schuh0de30f32020-12-06 12:44:28 -0800113using message_bridge::RemoteMessage;
Austin Schuh0afc4d12020-10-19 11:42:04 -0700114} // namespace
Austin Schuhe309d2a2019-11-29 13:25:21 -0800115
Brian Silverman1f345222020-09-24 21:14:48 -0700116Logger::Logger(EventLoop *event_loop, const Configuration *configuration,
117 std::function<bool(const Channel *)> should_log)
Austin Schuhe309d2a2019-11-29 13:25:21 -0800118 : event_loop_(event_loop),
Austin Schuh0c297012020-09-16 18:41:59 -0700119 configuration_(configuration),
120 name_(network::GetHostname()),
Brian Silverman1f345222020-09-24 21:14:48 -0700121 timer_handler_(event_loop_->AddTimer(
122 [this]() { DoLogData(event_loop_->monotonic_now()); })),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700123 server_statistics_fetcher_(
124 configuration::MultiNode(event_loop_->configuration())
125 ? event_loop_->MakeFetcher<message_bridge::ServerStatistics>(
126 "/aos")
127 : aos::Fetcher<message_bridge::ServerStatistics>()) {
Brian Silverman1f345222020-09-24 21:14:48 -0700128 VLOG(1) << "Creating logger for " << FlatbufferToJson(event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700129
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700130 // Find all the nodes which are logging timestamps on our node. This may
131 // over-estimate if should_log is specified.
132 std::vector<const Node *> timestamp_logger_nodes =
133 configuration::TimestampNodes(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700134
135 std::map<const Channel *, const Node *> timestamp_logger_channels;
136
137 // Now that we have all the nodes accumulated, make remote timestamp loggers
138 // for them.
139 for (const Node *node : timestamp_logger_nodes) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700140 // Note: since we are doing a find using the event loop channel, we need to
141 // make sure this channel pointer is part of the event loop configuration,
142 // not configuration_. This only matters when configuration_ !=
143 // event_loop->configuration();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700144 const Channel *channel = configuration::GetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700145 event_loop->configuration(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700146 absl::StrCat("/aos/remote_timestamps/", node->name()->string_view()),
Austin Schuh0de30f32020-12-06 12:44:28 -0800147 RemoteMessage::GetFullyQualifiedName(), event_loop_->name(),
Austin Schuh2f8fd752020-09-01 22:38:28 -0700148 event_loop_->node());
149
150 CHECK(channel != nullptr)
151 << ": Remote timestamps are logged on "
152 << event_loop_->node()->name()->string_view()
153 << " but can't find channel /aos/remote_timestamps/"
154 << node->name()->string_view();
Brian Silverman1f345222020-09-24 21:14:48 -0700155 if (!should_log(channel)) {
156 continue;
157 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700158 timestamp_logger_channels.insert(std::make_pair(channel, node));
159 }
160
Brian Silvermand90905f2020-09-23 14:42:56 -0700161 const size_t our_node_index =
162 configuration::GetNodeIndex(configuration_, event_loop_->node());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700163
Brian Silverman1f345222020-09-24 21:14:48 -0700164 for (size_t channel_index = 0;
165 channel_index < configuration_->channels()->size(); ++channel_index) {
166 const Channel *const config_channel =
167 configuration_->channels()->Get(channel_index);
Austin Schuh0c297012020-09-16 18:41:59 -0700168 // The MakeRawFetcher method needs a channel which is in the event loop
169 // configuration() object, not the configuration_ object. Go look that up
170 // from the config.
171 const Channel *channel = aos::configuration::GetChannel(
172 event_loop_->configuration(), config_channel->name()->string_view(),
173 config_channel->type()->string_view(), "", event_loop_->node());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700174 CHECK(channel != nullptr)
175 << ": Failed to look up channel "
176 << aos::configuration::CleanedChannelToString(config_channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700177 if (!should_log(channel)) {
178 continue;
179 }
Austin Schuh0c297012020-09-16 18:41:59 -0700180
Austin Schuhe309d2a2019-11-29 13:25:21 -0800181 FetcherStruct fs;
Brian Silverman1f345222020-09-24 21:14:48 -0700182 fs.channel_index = channel_index;
183 fs.channel = channel;
184
Austin Schuh6f3babe2020-01-26 20:34:50 -0800185 const bool is_local =
186 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
187
Austin Schuh15649d62019-12-28 16:36:38 -0800188 const bool is_readable =
189 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
Brian Silverman1f345222020-09-24 21:14:48 -0700190 const bool is_logged = configuration::ChannelMessageIsLoggedOnNode(
191 channel, event_loop_->node());
192 const bool log_message = is_logged && is_readable;
Austin Schuh15649d62019-12-28 16:36:38 -0800193
Brian Silverman1f345222020-09-24 21:14:48 -0700194 bool log_delivery_times = false;
195 if (event_loop_->node() != nullptr) {
196 log_delivery_times = configuration::ConnectionDeliveryTimeIsLoggedOnNode(
197 channel, event_loop_->node(), event_loop_->node());
198 }
Austin Schuh15649d62019-12-28 16:36:38 -0800199
Austin Schuh0de30f32020-12-06 12:44:28 -0800200 // Now, detect a RemoteMessage timestamp logger where we should just log the
Austin Schuh2f8fd752020-09-01 22:38:28 -0700201 // contents to a file directly.
202 const bool log_contents = timestamp_logger_channels.find(channel) !=
203 timestamp_logger_channels.end();
Austin Schuh2f8fd752020-09-01 22:38:28 -0700204
205 if (log_message || log_delivery_times || log_contents) {
Austin Schuh15649d62019-12-28 16:36:38 -0800206 fs.fetcher = event_loop->MakeRawFetcher(channel);
207 VLOG(1) << "Logging channel "
208 << configuration::CleanedChannelToString(channel);
209
210 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800211 VLOG(1) << " Delivery times";
Brian Silverman1f345222020-09-24 21:14:48 -0700212 fs.wants_timestamp_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800213 fs.timestamp_node_index = our_node_index;
Austin Schuh15649d62019-12-28 16:36:38 -0800214 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800215 if (log_message) {
216 VLOG(1) << " Data";
Brian Silverman1f345222020-09-24 21:14:48 -0700217 fs.wants_writer = true;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800218 if (!is_local) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800219 const Node *source_node = configuration::GetNode(
220 configuration_, channel->source_node()->string_view());
221 fs.data_node_index =
222 configuration::GetNodeIndex(configuration_, source_node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800223 fs.log_type = LogType::kLogRemoteMessage;
Austin Schuh315b96b2020-12-11 21:21:12 -0800224 } else {
225 fs.data_node_index = our_node_index;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800226 }
227 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700228 if (log_contents) {
229 VLOG(1) << "Timestamp logger channel "
230 << configuration::CleanedChannelToString(channel);
Brian Silverman1f345222020-09-24 21:14:48 -0700231 fs.timestamp_node = timestamp_logger_channels.find(channel)->second;
232 fs.wants_contents_writer = true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800233 fs.contents_node_index =
Brian Silverman1f345222020-09-24 21:14:48 -0700234 configuration::GetNodeIndex(configuration_, fs.timestamp_node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700235 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -0800237 }
Brian Silverman1f345222020-09-24 21:14:48 -0700238 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700239
240 // When we are logging remote timestamps, we need to be able to translate from
241 // the channel index that the event loop uses to the channel index in the
242 // config in the log file.
243 event_loop_to_logged_channel_index_.resize(
244 event_loop->configuration()->channels()->size(), -1);
245 for (size_t event_loop_channel_index = 0;
246 event_loop_channel_index <
247 event_loop->configuration()->channels()->size();
248 ++event_loop_channel_index) {
249 const Channel *event_loop_channel =
250 event_loop->configuration()->channels()->Get(event_loop_channel_index);
251
252 const Channel *logged_channel = aos::configuration::GetChannel(
253 configuration_, event_loop_channel->name()->string_view(),
254 event_loop_channel->type()->string_view(), "",
255 configuration::GetNode(configuration_, event_loop_->node()));
256
257 if (logged_channel != nullptr) {
258 event_loop_to_logged_channel_index_[event_loop_channel_index] =
259 configuration::ChannelIndex(configuration_, logged_channel);
260 }
261 }
Brian Silverman1f345222020-09-24 21:14:48 -0700262}
263
264Logger::~Logger() {
265 if (log_namer_) {
266 // If we are replaying a log file, or in simulation, we want to force the
267 // last bit of data to be logged. The easiest way to deal with this is to
268 // poll everything as we go to destroy the class, ie, shut down the logger,
269 // and write it to disk.
270 StopLogging(event_loop_->monotonic_now());
271 }
272}
273
Brian Silvermanae7c0332020-09-30 16:58:23 -0700274void Logger::StartLogging(std::unique_ptr<LogNamer> log_namer,
275 std::string_view log_start_uuid) {
Brian Silverman1f345222020-09-24 21:14:48 -0700276 CHECK(!log_namer_) << ": Already logging";
277 log_namer_ = std::move(log_namer);
Austin Schuh8c399962020-12-25 21:51:45 -0800278
279 std::string config_sha256;
280 if (separate_config_) {
281 flatbuffers::FlatBufferBuilder fbb;
282 flatbuffers::Offset<aos::Configuration> configuration_offset =
283 CopyFlatBuffer(configuration_, &fbb);
284 LogFileHeader::Builder log_file_header_builder(fbb);
285 log_file_header_builder.add_configuration(configuration_offset);
286 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
287 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> config_header(
288 fbb.Release());
289 config_sha256 = Sha256(config_header.span());
290 LOG(INFO) << "Config sha256 of " << config_sha256;
291 log_namer_->WriteConfiguration(&config_header, config_sha256);
292 }
293
Brian Silvermanae7c0332020-09-30 16:58:23 -0700294 log_event_uuid_ = UUID::Random();
295 log_start_uuid_ = log_start_uuid;
Brian Silverman1f345222020-09-24 21:14:48 -0700296 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
297
298 // We want to do as much work as possible before the initial Fetch. Time
299 // between that and actually starting to log opens up the possibility of
300 // falling off the end of the queue during that time.
301
302 for (FetcherStruct &f : fetchers_) {
303 if (f.wants_writer) {
304 f.writer = log_namer_->MakeWriter(f.channel);
305 }
306 if (f.wants_timestamp_writer) {
307 f.timestamp_writer = log_namer_->MakeTimestampWriter(f.channel);
308 }
309 if (f.wants_contents_writer) {
310 f.contents_writer = log_namer_->MakeForwardedTimestampWriter(
311 f.channel, CHECK_NOTNULL(f.timestamp_node));
312 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800313 }
314
Brian Silverman1f345222020-09-24 21:14:48 -0700315 CHECK(node_state_.empty());
Austin Schuh0c297012020-09-16 18:41:59 -0700316 node_state_.resize(configuration::MultiNode(configuration_)
317 ? configuration_->nodes()->size()
Austin Schuh2f8fd752020-09-01 22:38:28 -0700318 : 1u);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800319
Austin Schuh2f8fd752020-09-01 22:38:28 -0700320 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700321 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800322
Austin Schuh816e5d62021-01-05 23:42:20 -0800323 node_state_[node_index].log_file_header = MakeHeader(node, config_sha256);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700324 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800325
Austin Schuh2f8fd752020-09-01 22:38:28 -0700326 // Grab data from each channel right before we declare the log file started
327 // so we can capture the latest message on each channel. This lets us have
328 // non periodic messages with configuration that now get logged.
329 for (FetcherStruct &f : fetchers_) {
Brian Silvermancb805822020-10-06 17:43:35 -0700330 const auto start = event_loop_->monotonic_now();
331 const bool got_new = f.fetcher->Fetch();
332 const auto end = event_loop_->monotonic_now();
333 RecordFetchResult(start, end, got_new, &f);
334
335 // If there is a message, we want to write it.
336 f.written = f.fetcher->context().data == nullptr;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700337 }
338
339 // Clear out any old timestamps in case we are re-starting logging.
340 for (size_t i = 0; i < node_state_.size(); ++i) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800341 SetStartTime(i, monotonic_clock::min_time, realtime_clock::min_time,
342 monotonic_clock::min_time, realtime_clock::min_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700343 }
344
345 WriteHeader();
346
347 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
348 << " start_time " << last_synchronized_time_;
349
Austin Schuh315b96b2020-12-11 21:21:12 -0800350 // Force logging up until the start of the log file now, so the messages at
351 // the start are always ordered before the rest of the messages.
352 // Note: this ship may have already sailed, but we don't have to make it
353 // worse.
354 // TODO(austin): Test...
355 LogUntil(last_synchronized_time_);
356
Austin Schuh2f8fd752020-09-01 22:38:28 -0700357 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period_,
358 polling_period_);
359}
360
Brian Silverman1f345222020-09-24 21:14:48 -0700361std::unique_ptr<LogNamer> Logger::StopLogging(
362 aos::monotonic_clock::time_point end_time) {
363 CHECK(log_namer_) << ": Not logging right now";
364
365 if (end_time != aos::monotonic_clock::min_time) {
366 LogUntil(end_time);
367 }
368 timer_handler_->Disable();
369
370 for (FetcherStruct &f : fetchers_) {
371 f.writer = nullptr;
372 f.timestamp_writer = nullptr;
373 f.contents_writer = nullptr;
374 }
375 node_state_.clear();
376
Brian Silvermanae7c0332020-09-30 16:58:23 -0700377 log_event_uuid_ = UUID::Zero();
378 log_start_uuid_ = std::string();
379
Brian Silverman1f345222020-09-24 21:14:48 -0700380 return std::move(log_namer_);
381}
382
Austin Schuhfa895892020-01-07 20:07:41 -0800383void Logger::WriteHeader() {
Austin Schuh0c297012020-09-16 18:41:59 -0700384 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700385 server_statistics_fetcher_.Fetch();
386 }
387
388 aos::monotonic_clock::time_point monotonic_start_time =
389 event_loop_->monotonic_now();
390 aos::realtime_clock::time_point realtime_start_time =
391 event_loop_->realtime_now();
392
393 // We need to pick a point in time to declare the log file "started". This
394 // starts here. It needs to be after everything is fetched so that the
395 // fetchers are all pointed at the most recent message before the start
396 // time.
397 last_synchronized_time_ = monotonic_start_time;
398
Austin Schuh6f3babe2020-01-26 20:34:50 -0800399 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700400 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700401 MaybeUpdateTimestamp(node, node_index, monotonic_start_time,
402 realtime_start_time);
Austin Schuh315b96b2020-12-11 21:21:12 -0800403 MaybeWriteHeader(node_index, node);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800404 }
405}
Austin Schuh8bd96322020-02-13 21:18:22 -0800406
Austin Schuh315b96b2020-12-11 21:21:12 -0800407void Logger::MaybeWriteHeader(int node_index) {
408 if (configuration::MultiNode(configuration_)) {
409 return MaybeWriteHeader(node_index,
410 configuration_->nodes()->Get(node_index));
411 } else {
412 return MaybeWriteHeader(node_index, nullptr);
413 }
414}
415
416void Logger::MaybeWriteHeader(int node_index, const Node *node) {
417 // This function is responsible for writing the header when the header both
418 // has valid data, and when it needs to be written.
419 if (node_state_[node_index].header_written &&
420 node_state_[node_index].header_valid) {
421 // The header has been written and is valid, nothing to do.
422 return;
423 }
424 if (!node_state_[node_index].has_source_node_boot_uuid) {
425 // Can't write a header if we don't have the boot UUID.
426 return;
427 }
428
429 // WriteHeader writes the first header in a log file. We want to do this only
430 // once.
431 //
432 // Rotate rewrites the same header with a new part ID, but keeps the same part
433 // UUID. We don't want that when things reboot, because that implies that
434 // parts go together across a reboot.
435 //
436 // Reboot resets the parts UUID. So, once we've written a header the first
437 // time, we want to use Reboot to rotate the log and reset the parts UUID.
438 //
439 // header_valid is cleared whenever the remote reboots.
440 if (node_state_[node_index].header_written) {
441 log_namer_->Reboot(node, &node_state_[node_index].log_file_header);
442 } else {
443 log_namer_->WriteHeader(&node_state_[node_index].log_file_header, node);
444
445 node_state_[node_index].header_written = true;
446 }
447 node_state_[node_index].header_valid = true;
448}
449
Austin Schuh2f8fd752020-09-01 22:38:28 -0700450void Logger::WriteMissingTimestamps() {
Austin Schuh0c297012020-09-16 18:41:59 -0700451 if (configuration::MultiNode(configuration_)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700452 server_statistics_fetcher_.Fetch();
453 } else {
454 return;
455 }
456
457 if (server_statistics_fetcher_.get() == nullptr) {
458 return;
459 }
460
461 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700462 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700463 if (MaybeUpdateTimestamp(
464 node, node_index,
465 server_statistics_fetcher_.context().monotonic_event_time,
466 server_statistics_fetcher_.context().realtime_event_time)) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800467 CHECK(node_state_[node_index].header_written);
468 CHECK(node_state_[node_index].header_valid);
Austin Schuh64fab802020-09-09 22:47:47 -0700469 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh315b96b2020-12-11 21:21:12 -0800470 } else {
471 MaybeWriteHeader(node_index, node);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700472 }
473 }
474}
475
Austin Schuh315b96b2020-12-11 21:21:12 -0800476void Logger::SetStartTime(
477 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
478 aos::realtime_clock::time_point realtime_start_time,
479 aos::monotonic_clock::time_point logger_monotonic_start_time,
480 aos::realtime_clock::time_point logger_realtime_start_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700481 node_state_[node_index].monotonic_start_time = monotonic_start_time;
482 node_state_[node_index].realtime_start_time = realtime_start_time;
483 node_state_[node_index]
484 .log_file_header.mutable_message()
485 ->mutate_monotonic_start_time(
486 std::chrono::duration_cast<std::chrono::nanoseconds>(
487 monotonic_start_time.time_since_epoch())
488 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800489
490 // Add logger start times if they are available in the log file header.
491 if (node_state_[node_index]
492 .log_file_header.mutable_message()
493 ->has_logger_monotonic_start_time()) {
494 node_state_[node_index]
495 .log_file_header.mutable_message()
496 ->mutate_logger_monotonic_start_time(
497 std::chrono::duration_cast<std::chrono::nanoseconds>(
498 logger_monotonic_start_time.time_since_epoch())
499 .count());
500 }
501
502 if (node_state_[node_index]
503 .log_file_header.mutable_message()
504 ->has_logger_realtime_start_time()) {
505 node_state_[node_index]
506 .log_file_header.mutable_message()
507 ->mutate_logger_realtime_start_time(
508 std::chrono::duration_cast<std::chrono::nanoseconds>(
509 logger_realtime_start_time.time_since_epoch())
510 .count());
511 }
512
Austin Schuh2f8fd752020-09-01 22:38:28 -0700513 if (node_state_[node_index]
514 .log_file_header.mutable_message()
515 ->has_realtime_start_time()) {
516 node_state_[node_index]
517 .log_file_header.mutable_message()
518 ->mutate_realtime_start_time(
519 std::chrono::duration_cast<std::chrono::nanoseconds>(
520 realtime_start_time.time_since_epoch())
521 .count());
522 }
523}
524
525bool Logger::MaybeUpdateTimestamp(
526 const Node *node, int node_index,
527 aos::monotonic_clock::time_point monotonic_start_time,
528 aos::realtime_clock::time_point realtime_start_time) {
Brian Silverman87ac0402020-09-17 14:47:01 -0700529 // Bail early if the start times are already set.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700530 if (node_state_[node_index].monotonic_start_time !=
531 monotonic_clock::min_time) {
532 return false;
533 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800534 if (event_loop_->node() == node ||
535 !configuration::MultiNode(configuration_)) {
536 // There are no offsets to compute for ourself, so always succeed.
537 SetStartTime(node_index, monotonic_start_time, realtime_start_time,
538 monotonic_start_time, realtime_start_time);
539 node_state_[node_index].SetBootUUID(event_loop_->boot_uuid().string_view());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700540 return true;
Austin Schuh315b96b2020-12-11 21:21:12 -0800541 } else if (server_statistics_fetcher_.get() != nullptr) {
542 // We must be a remote node now. Look for the connection and see if it is
543 // connected.
544
545 for (const message_bridge::ServerConnection *connection :
546 *server_statistics_fetcher_->connections()) {
547 if (connection->node()->name()->string_view() !=
548 node->name()->string_view()) {
549 continue;
550 }
551
552 if (connection->state() != message_bridge::State::CONNECTED) {
553 VLOG(1) << node->name()->string_view()
554 << " is not connected, can't start it yet.";
555 break;
556 }
557
558 // Update the boot UUID as soon as we know we are connected.
559 if (!connection->has_boot_uuid()) {
560 VLOG(1) << "Missing boot_uuid for node " << aos::FlatbufferToJson(node);
561 break;
562 }
563
564 if (!node_state_[node_index].has_source_node_boot_uuid ||
565 node_state_[node_index].source_node_boot_uuid !=
566 connection->boot_uuid()->string_view()) {
567 node_state_[node_index].SetBootUUID(
568 connection->boot_uuid()->string_view());
569 }
570
571 if (!connection->has_monotonic_offset()) {
572 VLOG(1) << "Missing monotonic offset for setting start time for node "
573 << aos::FlatbufferToJson(node);
574 break;
575 }
576
577 // Found it and it is connected. Compensate and go.
578 SetStartTime(node_index,
579 monotonic_start_time +
580 std::chrono::nanoseconds(connection->monotonic_offset()),
581 realtime_start_time, monotonic_start_time,
582 realtime_start_time);
583 return true;
584 }
Austin Schuh2f8fd752020-09-01 22:38:28 -0700585 }
586 return false;
587}
588
589aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> Logger::MakeHeader(
Austin Schuh8c399962020-12-25 21:51:45 -0800590 const Node *node, std::string_view config_sha256) {
Austin Schuhfa895892020-01-07 20:07:41 -0800591 // Now write the header with this timestamp in it.
592 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800593 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800594
Austin Schuh8c399962020-12-25 21:51:45 -0800595 flatbuffers::Offset<aos::Configuration> configuration_offset;
596 if (!separate_config_) {
597 configuration_offset = CopyFlatBuffer(configuration_, &fbb);
598 } else {
599 CHECK(!config_sha256.empty());
600 }
Austin Schuhfa895892020-01-07 20:07:41 -0800601
Brian Silvermanae7c0332020-09-30 16:58:23 -0700602 const flatbuffers::Offset<flatbuffers::String> name_offset =
Austin Schuh0c297012020-09-16 18:41:59 -0700603 fbb.CreateString(name_);
Austin Schuhfa895892020-01-07 20:07:41 -0800604
Brian Silvermanae7c0332020-09-30 16:58:23 -0700605 CHECK(log_event_uuid_ != UUID::Zero());
606 const flatbuffers::Offset<flatbuffers::String> log_event_uuid_offset =
607 fbb.CreateString(log_event_uuid_.string_view());
Austin Schuh64fab802020-09-09 22:47:47 -0700608
Brian Silvermanae7c0332020-09-30 16:58:23 -0700609 const flatbuffers::Offset<flatbuffers::String> logger_instance_uuid_offset =
610 fbb.CreateString(logger_instance_uuid_.string_view());
611
612 flatbuffers::Offset<flatbuffers::String> log_start_uuid_offset;
613 if (!log_start_uuid_.empty()) {
614 log_start_uuid_offset = fbb.CreateString(log_start_uuid_);
615 }
616
Austin Schuh8c399962020-12-25 21:51:45 -0800617 flatbuffers::Offset<flatbuffers::String> config_sha256_offset;
618 if (!config_sha256.empty()) {
619 config_sha256_offset = fbb.CreateString(config_sha256);
620 }
621
Austin Schuh315b96b2020-12-11 21:21:12 -0800622 const flatbuffers::Offset<flatbuffers::String> logger_node_boot_uuid_offset =
623 fbb.CreateString(event_loop_->boot_uuid().string_view());
624
625 const flatbuffers::Offset<flatbuffers::String> source_node_boot_uuid_offset =
626 fbb.CreateString(event_loop_->boot_uuid().string_view());
Brian Silvermanae7c0332020-09-30 16:58:23 -0700627
628 const flatbuffers::Offset<flatbuffers::String> parts_uuid_offset =
Austin Schuh64fab802020-09-09 22:47:47 -0700629 fbb.CreateString("00000000-0000-4000-8000-000000000000");
630
Austin Schuhfa895892020-01-07 20:07:41 -0800631 flatbuffers::Offset<Node> node_offset;
Brian Silverman80993c22020-10-01 15:05:19 -0700632 flatbuffers::Offset<Node> logger_node_offset;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700633
Austin Schuh0c297012020-09-16 18:41:59 -0700634 if (configuration::MultiNode(configuration_)) {
Austin Schuha4fc60f2020-11-01 23:06:47 -0800635 node_offset = RecursiveCopyFlatBuffer(node, &fbb);
636 logger_node_offset = RecursiveCopyFlatBuffer(event_loop_->node(), &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800637 }
638
639 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
640
Austin Schuh64fab802020-09-09 22:47:47 -0700641 log_file_header_builder.add_name(name_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800642
643 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800644 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800645 log_file_header_builder.add_node(node_offset);
Brian Silverman80993c22020-10-01 15:05:19 -0700646 log_file_header_builder.add_logger_node(logger_node_offset);
Austin Schuhfa895892020-01-07 20:07:41 -0800647 }
648
Austin Schuh8c399962020-12-25 21:51:45 -0800649 if (!configuration_offset.IsNull()) {
650 log_file_header_builder.add_configuration(configuration_offset);
651 }
Austin Schuhfa895892020-01-07 20:07:41 -0800652 // The worst case theoretical out of order is the polling period times 2.
653 // One message could get logged right after the boundary, but be for right
654 // before the next boundary. And the reverse could happen for another
655 // message. Report back 3x to be extra safe, and because the cost isn't
656 // huge on the read side.
657 log_file_header_builder.add_max_out_of_order_duration(
Brian Silverman1f345222020-09-24 21:14:48 -0700658 std::chrono::nanoseconds(3 * polling_period_).count());
Austin Schuhfa895892020-01-07 20:07:41 -0800659
660 log_file_header_builder.add_monotonic_start_time(
661 std::chrono::duration_cast<std::chrono::nanoseconds>(
Austin Schuh2f8fd752020-09-01 22:38:28 -0700662 monotonic_clock::min_time.time_since_epoch())
Austin Schuhfa895892020-01-07 20:07:41 -0800663 .count());
Austin Schuh2f8fd752020-09-01 22:38:28 -0700664 if (node == event_loop_->node()) {
665 log_file_header_builder.add_realtime_start_time(
666 std::chrono::duration_cast<std::chrono::nanoseconds>(
667 realtime_clock::min_time.time_since_epoch())
668 .count());
Austin Schuh315b96b2020-12-11 21:21:12 -0800669 } else {
670 log_file_header_builder.add_logger_monotonic_start_time(
671 std::chrono::duration_cast<std::chrono::nanoseconds>(
672 monotonic_clock::min_time.time_since_epoch())
673 .count());
674 log_file_header_builder.add_logger_realtime_start_time(
675 std::chrono::duration_cast<std::chrono::nanoseconds>(
676 realtime_clock::min_time.time_since_epoch())
677 .count());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800678 }
679
Brian Silvermanae7c0332020-09-30 16:58:23 -0700680 log_file_header_builder.add_log_event_uuid(log_event_uuid_offset);
681 log_file_header_builder.add_logger_instance_uuid(logger_instance_uuid_offset);
682 if (!log_start_uuid_offset.IsNull()) {
683 log_file_header_builder.add_log_start_uuid(log_start_uuid_offset);
684 }
Austin Schuh315b96b2020-12-11 21:21:12 -0800685 log_file_header_builder.add_logger_node_boot_uuid(
686 logger_node_boot_uuid_offset);
687 log_file_header_builder.add_source_node_boot_uuid(
688 source_node_boot_uuid_offset);
Austin Schuh64fab802020-09-09 22:47:47 -0700689
690 log_file_header_builder.add_parts_uuid(parts_uuid_offset);
691 log_file_header_builder.add_parts_index(0);
692
Austin Schuh8c399962020-12-25 21:51:45 -0800693 log_file_header_builder.add_configuration_sha256(0);
694
695 if (!config_sha256_offset.IsNull()) {
696 log_file_header_builder.add_configuration_sha256(config_sha256_offset);
697 }
698
Austin Schuh2f8fd752020-09-01 22:38:28 -0700699 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuha4fc60f2020-11-01 23:06:47 -0800700 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> result(
701 fbb.Release());
702
703 CHECK(result.Verify()) << ": Built a corrupted header.";
704
705 return result;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700706}
707
Brian Silvermancb805822020-10-06 17:43:35 -0700708void Logger::ResetStatisics() {
709 max_message_fetch_time_ = std::chrono::nanoseconds::zero();
710 max_message_fetch_time_channel_ = -1;
711 max_message_fetch_time_size_ = -1;
712 total_message_fetch_time_ = std::chrono::nanoseconds::zero();
713 total_message_fetch_count_ = 0;
714 total_message_fetch_bytes_ = 0;
715 total_nop_fetch_time_ = std::chrono::nanoseconds::zero();
716 total_nop_fetch_count_ = 0;
717 max_copy_time_ = std::chrono::nanoseconds::zero();
718 max_copy_time_channel_ = -1;
719 max_copy_time_size_ = -1;
720 total_copy_time_ = std::chrono::nanoseconds::zero();
721 total_copy_count_ = 0;
722 total_copy_bytes_ = 0;
723}
724
Austin Schuh2f8fd752020-09-01 22:38:28 -0700725void Logger::Rotate() {
726 for (const Node *node : log_namer_->nodes()) {
Brian Silvermand90905f2020-09-23 14:42:56 -0700727 const int node_index = configuration::GetNodeIndex(configuration_, node);
Austin Schuh64fab802020-09-09 22:47:47 -0700728 log_namer_->Rotate(node, &node_state_[node_index].log_file_header);
Austin Schuh2f8fd752020-09-01 22:38:28 -0700729 }
730}
731
732void Logger::LogUntil(monotonic_clock::time_point t) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800733 // Grab the latest ServerStatistics message. This will always have the
734 // oppertunity to be >= to the current time, so it will always represent any
735 // reboots which may have happened.
Austin Schuh2f8fd752020-09-01 22:38:28 -0700736 WriteMissingTimestamps();
737
738 // Write each channel to disk, one at a time.
739 for (FetcherStruct &f : fetchers_) {
740 while (true) {
741 if (f.written) {
Brian Silvermancb805822020-10-06 17:43:35 -0700742 const auto start = event_loop_->monotonic_now();
743 const bool got_new = f.fetcher->FetchNext();
744 const auto end = event_loop_->monotonic_now();
745 RecordFetchResult(start, end, got_new, &f);
746 if (!got_new) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700747 VLOG(2) << "No new data on "
748 << configuration::CleanedChannelToString(
749 f.fetcher->channel());
750 break;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700751 }
Brian Silvermancb805822020-10-06 17:43:35 -0700752 f.written = false;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700753 }
754
Austin Schuh2f8fd752020-09-01 22:38:28 -0700755 // TODO(james): Write tests to exercise this logic.
Brian Silvermancb805822020-10-06 17:43:35 -0700756 if (f.fetcher->context().monotonic_event_time >= t) {
Austin Schuh2f8fd752020-09-01 22:38:28 -0700757 break;
758 }
Brian Silvermancb805822020-10-06 17:43:35 -0700759 if (f.writer != nullptr) {
760 // Write!
761 const auto start = event_loop_->monotonic_now();
762 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
763 max_header_size_);
764 fbb.ForceDefaults(true);
765
766 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
767 f.channel_index, f.log_type));
768 const auto end = event_loop_->monotonic_now();
769 RecordCreateMessageTime(start, end, &f);
770
771 VLOG(2) << "Writing data as node "
772 << FlatbufferToJson(event_loop_->node()) << " for channel "
773 << configuration::CleanedChannelToString(f.fetcher->channel())
774 << " to " << f.writer->filename() << " data "
775 << FlatbufferToJson(
776 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
777 fbb.GetBufferPointer()));
778
779 max_header_size_ = std::max(max_header_size_,
780 fbb.GetSize() - f.fetcher->context().size);
Austin Schuh315b96b2020-12-11 21:21:12 -0800781 CHECK(node_state_[f.data_node_index].header_valid)
782 << ": Can't write data before the header on channel "
783 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700784 f.writer->QueueSizedFlatbuffer(&fbb);
785 }
786
787 if (f.timestamp_writer != nullptr) {
788 // And now handle timestamps.
789 const auto start = event_loop_->monotonic_now();
790 flatbuffers::FlatBufferBuilder fbb;
791 fbb.ForceDefaults(true);
792
793 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
794 f.channel_index,
795 LogType::kLogDeliveryTimeOnly));
796 const auto end = event_loop_->monotonic_now();
797 RecordCreateMessageTime(start, end, &f);
798
799 VLOG(2) << "Writing timestamps as node "
800 << FlatbufferToJson(event_loop_->node()) << " for channel "
801 << configuration::CleanedChannelToString(f.fetcher->channel())
802 << " to " << f.timestamp_writer->filename() << " timestamp "
803 << FlatbufferToJson(
804 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
805 fbb.GetBufferPointer()));
806
Austin Schuh315b96b2020-12-11 21:21:12 -0800807 CHECK(node_state_[f.timestamp_node_index].header_valid)
808 << ": Can't write data before the header on channel "
809 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700810 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
811 }
812
813 if (f.contents_writer != nullptr) {
814 const auto start = event_loop_->monotonic_now();
815 // And now handle the special message contents channel. Copy the
816 // message into a FlatBufferBuilder and save it to disk.
817 // TODO(austin): We can be more efficient here when we start to
818 // care...
819 flatbuffers::FlatBufferBuilder fbb;
820 fbb.ForceDefaults(true);
821
Austin Schuh0de30f32020-12-06 12:44:28 -0800822 const RemoteMessage *msg =
823 flatbuffers::GetRoot<RemoteMessage>(f.fetcher->context().data);
Brian Silvermancb805822020-10-06 17:43:35 -0700824
Austin Schuh315b96b2020-12-11 21:21:12 -0800825 CHECK(msg->has_boot_uuid()) << ": " << aos::FlatbufferToJson(msg);
826 if (!node_state_[f.contents_node_index].has_source_node_boot_uuid ||
827 node_state_[f.contents_node_index].source_node_boot_uuid !=
828 msg->boot_uuid()->string_view()) {
829 node_state_[f.contents_node_index].SetBootUUID(
830 msg->boot_uuid()->string_view());
831
832 MaybeWriteHeader(f.contents_node_index);
833 }
834
Brian Silvermancb805822020-10-06 17:43:35 -0700835 logger::MessageHeader::Builder message_header_builder(fbb);
836
837 // TODO(austin): This needs to check the channel_index and confirm
838 // that it should be logged before squirreling away the timestamp to
839 // disk. We don't want to log irrelevant timestamps.
840
841 // Note: this must match the same order as MessageBridgeServer and
842 // PackMessage. We want identical headers to have identical
843 // on-the-wire formats to make comparing them easier.
844
845 // Translate from the channel index that the event loop uses to the
846 // channel index in the log file.
847 message_header_builder.add_channel_index(
848 event_loop_to_logged_channel_index_[msg->channel_index()]);
849
850 message_header_builder.add_queue_index(msg->queue_index());
851 message_header_builder.add_monotonic_sent_time(
852 msg->monotonic_sent_time());
853 message_header_builder.add_realtime_sent_time(
854 msg->realtime_sent_time());
855
856 message_header_builder.add_monotonic_remote_time(
857 msg->monotonic_remote_time());
858 message_header_builder.add_realtime_remote_time(
859 msg->realtime_remote_time());
860 message_header_builder.add_remote_queue_index(
861 msg->remote_queue_index());
862
Austin Schuh969cd602021-01-03 00:09:45 -0800863 message_header_builder.add_monotonic_timestamp_time(
864 f.fetcher->context()
865 .monotonic_event_time.time_since_epoch()
866 .count());
867
Brian Silvermancb805822020-10-06 17:43:35 -0700868 fbb.FinishSizePrefixed(message_header_builder.Finish());
869 const auto end = event_loop_->monotonic_now();
870 RecordCreateMessageTime(start, end, &f);
871
Austin Schuh315b96b2020-12-11 21:21:12 -0800872 CHECK(node_state_[f.contents_node_index].header_valid)
873 << ": Can't write data before the header on channel "
874 << configuration::CleanedChannelToString(f.fetcher->channel());
Brian Silvermancb805822020-10-06 17:43:35 -0700875 f.contents_writer->QueueSizedFlatbuffer(&fbb);
876 }
877
878 f.written = true;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700879 }
880 }
881 last_synchronized_time_ = t;
Austin Schuhfa895892020-01-07 20:07:41 -0800882}
883
Brian Silverman1f345222020-09-24 21:14:48 -0700884void Logger::DoLogData(const monotonic_clock::time_point end_time) {
885 // We want to guarantee that messages aren't out of order by more than
Austin Schuhe309d2a2019-11-29 13:25:21 -0800886 // max_out_of_order_duration. To do this, we need sync points. Every write
887 // cycle should be a sync point.
Austin Schuhe309d2a2019-11-29 13:25:21 -0800888
889 do {
890 // Move the sync point up by at most polling_period. This forces one sync
891 // per iteration, even if it is small.
Brian Silverman1f345222020-09-24 21:14:48 -0700892 LogUntil(std::min(last_synchronized_time_ + polling_period_, end_time));
893
894 on_logged_period_();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800895
Austin Schuhe309d2a2019-11-29 13:25:21 -0800896 // If we missed cycles, we could be pretty far behind. Spin until we are
897 // caught up.
Brian Silverman1f345222020-09-24 21:14:48 -0700898 } while (last_synchronized_time_ + polling_period_ < end_time);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800899}
900
Brian Silvermancb805822020-10-06 17:43:35 -0700901void Logger::RecordFetchResult(aos::monotonic_clock::time_point start,
902 aos::monotonic_clock::time_point end,
903 bool got_new, FetcherStruct *fetcher) {
904 const auto duration = end - start;
905 if (!got_new) {
906 ++total_nop_fetch_count_;
907 total_nop_fetch_time_ += duration;
908 return;
909 }
910 ++total_message_fetch_count_;
911 total_message_fetch_bytes_ += fetcher->fetcher->context().size;
912 total_message_fetch_time_ += duration;
913 if (duration > max_message_fetch_time_) {
914 max_message_fetch_time_ = duration;
915 max_message_fetch_time_channel_ = fetcher->channel_index;
916 max_message_fetch_time_size_ = fetcher->fetcher->context().size;
917 }
918}
919
920void Logger::RecordCreateMessageTime(aos::monotonic_clock::time_point start,
921 aos::monotonic_clock::time_point end,
922 FetcherStruct *fetcher) {
923 const auto duration = end - start;
924 total_copy_time_ += duration;
925 ++total_copy_count_;
926 total_copy_bytes_ += fetcher->fetcher->context().size;
927 if (duration > max_copy_time_) {
928 max_copy_time_ = duration;
929 max_copy_time_channel_ = fetcher->channel_index;
930 max_copy_time_size_ = fetcher->fetcher->context().size;
931 }
932}
933
Austin Schuh11d43732020-09-21 17:28:30 -0700934std::vector<std::vector<std::string>> ToLogReaderVector(
935 const std::vector<LogFile> &log_files) {
936 std::vector<std::vector<std::string>> result;
937 for (const LogFile &log_file : log_files) {
938 for (const LogParts &log_parts : log_file.parts) {
939 std::vector<std::string> parts;
940 for (const std::string &part : log_parts.parts) {
941 parts.emplace_back(part);
942 }
943 result.emplace_back(std::move(parts));
944 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700945 }
946 return result;
947}
948
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800949LogReader::LogReader(std::string_view filename,
950 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800951 : LogReader(SortParts({std::string(filename)}), replay_configuration) {}
Austin Schuhfa895892020-01-07 20:07:41 -0800952
Austin Schuh287d43d2020-12-04 20:19:33 -0800953LogReader::LogReader(std::vector<LogFile> log_files,
Austin Schuhfa895892020-01-07 20:07:41 -0800954 const Configuration *replay_configuration)
Austin Schuh287d43d2020-12-04 20:19:33 -0800955 : log_files_(std::move(log_files)),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800956 replay_configuration_(replay_configuration) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800957 CHECK_GT(log_files_.size(), 0u);
958 {
959 // Validate that we have the same config everwhere. This will be true if
960 // all the parts were sorted together and the configs match.
961 const Configuration *config = nullptr;
Austin Schuh297d2352021-01-21 19:02:17 -0800962 for (const LogFile &log_file : log_files_) {
963 if (log_file.config.get() == nullptr) {
964 LOG(FATAL) << "Couldn't find a config in " << log_file;
965 }
Austin Schuh0ca51f32020-12-25 21:51:45 -0800966 if (config == nullptr) {
967 config = log_file.config.get();
968 } else {
969 CHECK_EQ(config, log_file.config.get());
970 }
971 }
972 }
Austin Schuhdda74ec2021-01-03 19:30:37 -0800973
Austin Schuh6331ef92020-01-07 18:28:09 -0800974 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800975
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700976 // Remap all existing remote timestamp channels. They will be recreated, and
977 // the data logged isn't relevant anymore.
Austin Schuh3c5dae52020-10-06 18:55:18 -0700978 for (const Node *node : configuration::GetNodes(logged_configuration())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -0700979 std::vector<const Node *> timestamp_logger_nodes =
980 configuration::TimestampNodes(logged_configuration(), node);
981 for (const Node *remote_node : timestamp_logger_nodes) {
982 const std::string channel = absl::StrCat(
983 "/aos/remote_timestamps/", remote_node->name()->string_view());
Austin Schuh0de30f32020-12-06 12:44:28 -0800984 // See if the log file is an old log with MessageHeader channels in it, or
985 // a newer log with RemoteMessage. If we find an older log, rename the
986 // type too along with the name.
987 if (HasChannel<MessageHeader>(channel, node)) {
988 CHECK(!HasChannel<RemoteMessage>(channel, node))
989 << ": Can't have both a MessageHeader and RemoteMessage remote "
990 "timestamp channel.";
James Kuszmaul4f106fb2021-01-05 20:53:02 -0800991 // In theory, we should check NOT_LOGGED like RemoteMessage and be more
992 // careful about updating the config, but there are fewer and fewer logs
993 // with MessageHeader remote messages, so it isn't worth the effort.
Austin Schuh0de30f32020-12-06 12:44:28 -0800994 RemapLoggedChannel<MessageHeader>(channel, node, "/original",
995 "aos.message_bridge.RemoteMessage");
996 } else {
997 CHECK(HasChannel<RemoteMessage>(channel, node))
998 << ": Failed to find {\"name\": \"" << channel << "\", \"type\": \""
999 << RemoteMessage::GetFullyQualifiedName() << "\"} for node "
1000 << node->name()->string_view();
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001001 // Only bother to remap if there's something on the channel. We can
1002 // tell if the channel was marked NOT_LOGGED or not. This makes the
1003 // config not change un-necesarily when we replay a log with NOT_LOGGED
1004 // messages.
1005 if (HasLoggedChannel<RemoteMessage>(channel, node)) {
1006 RemapLoggedChannel<RemoteMessage>(channel, node);
1007 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001008 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001009 }
1010 }
1011
Austin Schuh6aa77be2020-02-22 21:06:40 -08001012 if (replay_configuration) {
1013 CHECK_EQ(configuration::MultiNode(configuration()),
1014 configuration::MultiNode(replay_configuration))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001015 << ": Log file and replay config need to both be multi or single "
1016 "node.";
Austin Schuh6aa77be2020-02-22 21:06:40 -08001017 }
1018
Austin Schuh6f3babe2020-01-26 20:34:50 -08001019 if (!configuration::MultiNode(configuration())) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001020 states_.emplace_back(std::make_unique<State>(
1021 std::make_unique<TimestampMapper>(FilterPartsForNode(log_files_, ""))));
Austin Schuh8bd96322020-02-13 21:18:22 -08001022 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001023 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -07001024 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -08001025 replay_configuration->nodes()->size())
Austin Schuh2f8fd752020-09-01 22:38:28 -07001026 << ": Log file and replay config need to have matching nodes "
1027 "lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001028 for (const Node *node : *logged_configuration()->nodes()) {
1029 if (configuration::GetNode(replay_configuration, node) == nullptr) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001030 LOG(FATAL) << "Found node " << FlatbufferToJson(node)
1031 << " in logged config that is not present in the replay "
1032 "config.";
James Kuszmaul46d82582020-05-09 19:50:09 -07001033 }
1034 }
Austin Schuh6aa77be2020-02-22 21:06:40 -08001035 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001036 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -08001037 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001038}
1039
Austin Schuh6aa77be2020-02-22 21:06:40 -08001040LogReader::~LogReader() {
Austin Schuh39580f12020-08-01 14:44:08 -07001041 if (event_loop_factory_unique_ptr_) {
1042 Deregister();
1043 } else if (event_loop_factory_ != nullptr) {
1044 LOG(FATAL) << "Must call Deregister before the SimulatedEventLoopFactory "
1045 "is destroyed";
1046 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001047 // Zero out some buffers. It's easy to do use-after-frees on these, so make
1048 // it more obvious.
Austin Schuh39580f12020-08-01 14:44:08 -07001049 if (remapped_configuration_buffer_) {
1050 remapped_configuration_buffer_->Wipe();
1051 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001052}
Austin Schuhe309d2a2019-11-29 13:25:21 -08001053
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001054const Configuration *LogReader::logged_configuration() const {
Austin Schuh0ca51f32020-12-25 21:51:45 -08001055 return log_files_[0].config.get();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001056}
1057
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001058const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001059 return remapped_configuration_;
1060}
1061
Austin Schuh07676622021-01-21 18:59:17 -08001062std::vector<const Node *> LogReader::LoggedNodes() const {
1063 return configuration::GetNodes(logged_configuration());
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001064}
Austin Schuh15649d62019-12-28 16:36:38 -08001065
Austin Schuh11d43732020-09-21 17:28:30 -07001066monotonic_clock::time_point LogReader::monotonic_start_time(
1067 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001068 State *state =
1069 states_[configuration::GetNodeIndex(configuration(), node)].get();
1070 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1071
Austin Schuh858c9f32020-08-31 16:56:12 -07001072 return state->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001073}
1074
Austin Schuh11d43732020-09-21 17:28:30 -07001075realtime_clock::time_point LogReader::realtime_start_time(
1076 const Node *node) const {
Austin Schuh8bd96322020-02-13 21:18:22 -08001077 State *state =
1078 states_[configuration::GetNodeIndex(configuration(), node)].get();
1079 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
1080
Austin Schuh858c9f32020-08-31 16:56:12 -07001081 return state->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001082}
1083
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001084void LogReader::Register() {
1085 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -08001086 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001087 Register(event_loop_factory_unique_ptr_.get());
1088}
1089
Austin Schuh92547522019-12-28 14:33:43 -08001090void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -08001091 event_loop_factory_ = event_loop_factory;
Austin Schuhe5bbd9e2020-09-21 17:29:20 -07001092 remapped_configuration_ = event_loop_factory_->configuration();
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001093 filters_ =
1094 std::make_unique<message_bridge::MultiNodeNoncausalOffsetEstimator>(
Austin Schuhba20ea72021-01-21 16:47:01 -08001095 event_loop_factory_->configuration(), logged_configuration(),
Austin Schuhfe3fb342021-01-16 18:50:37 -08001096 FLAGS_skip_order_validation,
1097 chrono::duration_cast<chrono::nanoseconds>(
1098 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh92547522019-12-28 14:33:43 -08001099
Austin Schuhe639ea12021-01-25 13:00:22 -08001100 std::vector<TimestampMapper *> timestamp_mappers;
Brian Silvermand90905f2020-09-23 14:42:56 -07001101 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001102 const size_t node_index =
1103 configuration::GetNodeIndex(configuration(), node);
Austin Schuh287d43d2020-12-04 20:19:33 -08001104 std::vector<LogParts> filtered_parts = FilterPartsForNode(
1105 log_files_, node != nullptr ? node->name()->string_view() : "");
Austin Schuh315b96b2020-12-11 21:21:12 -08001106
1107 // Confirm that all the parts are from the same boot if there are enough
1108 // parts to not be from the same boot.
1109 if (filtered_parts.size() > 1u) {
1110 for (size_t i = 1; i < filtered_parts.size(); ++i) {
1111 CHECK_EQ(filtered_parts[i].source_boot_uuid,
1112 filtered_parts[0].source_boot_uuid)
1113 << ": Found parts from different boots "
1114 << LogFileVectorToString(log_files_);
1115 }
James Kuszmaul4f106fb2021-01-05 20:53:02 -08001116 if (!filtered_parts[0].source_boot_uuid.empty()) {
1117 event_loop_factory_->GetNodeEventLoopFactory(node)->set_boot_uuid(
1118 filtered_parts[0].source_boot_uuid);
1119 }
Austin Schuh315b96b2020-12-11 21:21:12 -08001120 }
1121
Austin Schuh287d43d2020-12-04 20:19:33 -08001122 states_[node_index] = std::make_unique<State>(
1123 filtered_parts.size() == 0u
1124 ? nullptr
1125 : std::make_unique<TimestampMapper>(std::move(filtered_parts)));
Austin Schuh8bd96322020-02-13 21:18:22 -08001126 State *state = states_[node_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001127 state->set_event_loop(state->SetNodeEventLoopFactory(
Austin Schuh858c9f32020-08-31 16:56:12 -07001128 event_loop_factory_->GetNodeEventLoopFactory(node)));
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001129
1130 state->SetChannelCount(logged_configuration()->channels()->size());
Austin Schuhe639ea12021-01-25 13:00:22 -08001131 timestamp_mappers.emplace_back(state->timestamp_mapper());
Austin Schuhcde938c2020-02-02 17:30:07 -08001132 }
Austin Schuhe639ea12021-01-25 13:00:22 -08001133 filters_->SetTimestampMappers(std::move(timestamp_mappers));
1134
1135 // Note: this needs to be set before any times are pulled, or we won't observe
1136 // the timestamps.
Austin Schuh87dd3832021-01-01 23:07:31 -08001137 event_loop_factory_->SetTimeConverter(filters_.get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001138
Austin Schuh287d43d2020-12-04 20:19:33 -08001139 for (const Node *node : configuration::GetNodes(configuration())) {
1140 const size_t node_index =
1141 configuration::GetNodeIndex(configuration(), node);
1142 State *state = states_[node_index].get();
1143 for (const Node *other_node : configuration::GetNodes(configuration())) {
1144 const size_t other_node_index =
1145 configuration::GetNodeIndex(configuration(), other_node);
1146 State *other_state = states_[other_node_index].get();
1147 if (other_state != state) {
1148 state->AddPeer(other_state);
1149 }
1150 }
1151 }
1152
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001153 // Register after making all the State objects so we can build references
1154 // between them.
1155 for (const Node *node : configuration::GetNodes(configuration())) {
1156 const size_t node_index =
1157 configuration::GetNodeIndex(configuration(), node);
1158 State *state = states_[node_index].get();
1159
1160 Register(state->event_loop());
1161 }
1162
James Kuszmaul46d82582020-05-09 19:50:09 -07001163 if (live_nodes_ == 0) {
1164 LOG(FATAL)
1165 << "Don't have logs from any of the nodes in the replay config--are "
1166 "you sure that the replay config matches the original config?";
1167 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001168
Austin Schuh87dd3832021-01-01 23:07:31 -08001169 filters_->CheckGraph();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001170
Austin Schuh858c9f32020-08-31 16:56:12 -07001171 for (std::unique_ptr<State> &state : states_) {
1172 state->SeedSortedMessages();
1173 }
1174
Austin Schuh2f8fd752020-09-01 22:38:28 -07001175 // We want to start the log file at the last start time of the log files
1176 // from all the nodes. Compute how long each node's simulation needs to run
1177 // to move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -08001178 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -08001179
Austin Schuh2f8fd752020-09-01 22:38:28 -07001180 // TODO(austin): We want an "OnStart" callback for each node rather than
1181 // running until the last node.
1182
Austin Schuh8bd96322020-02-13 21:18:22 -08001183 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001184 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1185 << MaybeNodeName(state->event_loop()->node()) << "now "
1186 << state->monotonic_now();
Austin Schuh287d43d2020-12-04 20:19:33 -08001187 if (state->monotonic_start_time() == monotonic_clock::min_time) {
1188 continue;
1189 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001190 // And start computing the start time on the distributed clock now that
1191 // that works.
Austin Schuh858c9f32020-08-31 16:56:12 -07001192 start_time = std::max(
1193 start_time, state->ToDistributedClock(state->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -08001194 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001195
Austin Schuh87dd3832021-01-01 23:07:31 -08001196 // TODO(austin): If a node doesn't have a start time, we might not queue
1197 // enough. If this happens, we'll explode with a frozen error eventually.
1198
Austin Schuh2f8fd752020-09-01 22:38:28 -07001199 CHECK_GE(start_time, distributed_clock::epoch())
1200 << ": Hmm, we have a node starting before the start of time. Offset "
1201 "everything.";
Austin Schuhcde938c2020-02-02 17:30:07 -08001202
Austin Schuh6f3babe2020-01-26 20:34:50 -08001203 // Forwarding is tracked per channel. If it is enabled, we want to turn it
1204 // off. Otherwise messages replayed will get forwarded across to the other
Austin Schuh2f8fd752020-09-01 22:38:28 -07001205 // nodes, and also replayed on the other nodes. This may not satisfy all
1206 // our users, but it'll start the discussion.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001207 if (configuration::MultiNode(event_loop_factory_->configuration())) {
1208 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
1209 const Channel *channel = logged_configuration()->channels()->Get(i);
1210 const Node *node = configuration::GetNode(
1211 configuration(), channel->source_node()->string_view());
1212
Austin Schuh8bd96322020-02-13 21:18:22 -08001213 State *state =
1214 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001215
1216 const Channel *remapped_channel =
Austin Schuh858c9f32020-08-31 16:56:12 -07001217 RemapChannel(state->event_loop(), channel);
Austin Schuh6f3babe2020-01-26 20:34:50 -08001218
1219 event_loop_factory_->DisableForwarding(remapped_channel);
1220 }
Austin Schuh4c3b9702020-08-30 11:34:55 -07001221
1222 // If we are replaying a log, we don't want a bunch of redundant messages
1223 // from both the real message bridge and simulated message bridge.
1224 event_loop_factory_->DisableStatistics();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001225 }
1226
Austin Schuhcde938c2020-02-02 17:30:07 -08001227 // While we are starting the system up, we might be relying on matching data
1228 // to timestamps on log files where the timestamp log file starts before the
1229 // data. In this case, it is reasonable to expect missing data.
Austin Schuhdda74ec2021-01-03 19:30:37 -08001230 {
1231 const bool prior_ignore_missing_data = ignore_missing_data_;
1232 ignore_missing_data_ = true;
1233 VLOG(1) << "Running until " << start_time << " in Register";
1234 event_loop_factory_->RunFor(start_time.time_since_epoch());
1235 VLOG(1) << "At start time";
1236 // Now that we are running for real, missing data means that the log file is
1237 // corrupted or went wrong.
1238 ignore_missing_data_ = prior_ignore_missing_data;
1239 }
Austin Schuh92547522019-12-28 14:33:43 -08001240
Austin Schuh8bd96322020-02-13 21:18:22 -08001241 for (std::unique_ptr<State> &state : states_) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001242 // Make the RT clock be correct before handing it to the user.
1243 if (state->realtime_start_time() != realtime_clock::min_time) {
1244 state->SetRealtimeOffset(state->monotonic_start_time(),
1245 state->realtime_start_time());
1246 }
1247 VLOG(1) << "Start time is " << state->monotonic_start_time() << " for node "
1248 << MaybeNodeName(state->event_loop()->node()) << "now "
1249 << state->monotonic_now();
1250 }
1251
1252 if (FLAGS_timestamps_to_csv) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001253 filters_->Start(event_loop_factory);
Austin Schuh8bd96322020-02-13 21:18:22 -08001254 }
1255}
1256
Austin Schuh2f8fd752020-09-01 22:38:28 -07001257message_bridge::NoncausalOffsetEstimator *LogReader::GetFilter(
Austin Schuh8bd96322020-02-13 21:18:22 -08001258 const Node *node_a, const Node *node_b) {
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001259 if (filters_) {
1260 return filters_->GetFilter(node_a, node_b);
Austin Schuh8bd96322020-02-13 21:18:22 -08001261 }
Austin Schuh0ca1fd32020-12-18 22:53:05 -08001262 return nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001263}
1264
Austin Schuhe309d2a2019-11-29 13:25:21 -08001265void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001266 State *state =
1267 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
1268 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001269
Austin Schuh858c9f32020-08-31 16:56:12 -07001270 state->set_event_loop(event_loop);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001271
Tyler Chatow67ddb032020-01-12 14:30:04 -08001272 // We don't run timing reports when trying to print out logged data, because
1273 // otherwise we would end up printing out the timing reports themselves...
1274 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -08001275 event_loop->SkipTimingReport();
1276 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -08001277
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001278 for (size_t logged_channel_index = 0;
1279 logged_channel_index < logged_configuration()->channels()->size();
1280 ++logged_channel_index) {
1281 const Channel *channel = RemapChannel(
1282 event_loop,
1283 logged_configuration()->channels()->Get(logged_channel_index));
Austin Schuh8bd96322020-02-13 21:18:22 -08001284
Austin Schuh532656d2021-01-11 10:17:18 -08001285 if (channel->logger() == LoggerConfig::NOT_LOGGED) {
1286 continue;
1287 }
1288
Austin Schuh2f8fd752020-09-01 22:38:28 -07001289 message_bridge::NoncausalOffsetEstimator *filter = nullptr;
Austin Schuh969cd602021-01-03 00:09:45 -08001290 RemoteMessageSender *remote_timestamp_sender = nullptr;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001291
1292 State *source_state = nullptr;
Austin Schuh8bd96322020-02-13 21:18:22 -08001293
1294 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
1295 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001296 // We've got a message which is being forwarded to this node.
1297 const Node *source_node = configuration::GetNode(
Austin Schuh8bd96322020-02-13 21:18:22 -08001298 event_loop->configuration(), channel->source_node()->string_view());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001299 filter = GetFilter(event_loop->node(), source_node);
Austin Schuh8bd96322020-02-13 21:18:22 -08001300
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001301 // Delivery timestamps are supposed to be logged back on the source node.
1302 // Configure remote timestamps to be sent.
1303 const bool delivery_time_is_logged =
1304 configuration::ConnectionDeliveryTimeIsLoggedOnNode(
1305 channel, event_loop->node(), source_node);
1306
1307 source_state =
1308 states_[configuration::GetNodeIndex(configuration(), source_node)]
1309 .get();
1310
1311 if (delivery_time_is_logged) {
1312 remote_timestamp_sender =
1313 source_state->RemoteTimestampSender(event_loop->node());
Austin Schuh8bd96322020-02-13 21:18:22 -08001314 }
1315 }
Austin Schuh858c9f32020-08-31 16:56:12 -07001316
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001317 state->SetChannel(
1318 logged_channel_index,
1319 configuration::ChannelIndex(event_loop->configuration(), channel),
1320 event_loop->MakeRawSender(channel), filter, remote_timestamp_sender,
1321 source_state);
Austin Schuhe309d2a2019-11-29 13:25:21 -08001322 }
1323
Austin Schuh6aa77be2020-02-22 21:06:40 -08001324 // If we didn't find any log files with data in them, we won't ever get a
1325 // callback or be live. So skip the rest of the setup.
Austin Schuh287d43d2020-12-04 20:19:33 -08001326 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001327 return;
1328 }
1329
Austin Schuh858c9f32020-08-31 16:56:12 -07001330 state->set_timer_handler(event_loop->AddTimer([this, state]() {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001331 VLOG(1) << "Starting sending " << MaybeNodeName(state->event_loop()->node())
1332 << "at " << state->event_loop()->context().monotonic_event_time
1333 << " now " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001334 if (state->OldestMessageTime() == monotonic_clock::max_time) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001335 --live_nodes_;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001336 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Node down!";
James Kuszmaul71a81932020-12-15 21:08:01 -08001337 if (exit_on_finish_ && live_nodes_ == 0) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001338 event_loop_factory_->Exit();
1339 }
James Kuszmaul314f1672020-01-03 20:02:08 -08001340 return;
1341 }
Austin Schuh2f8fd752020-09-01 22:38:28 -07001342
Austin Schuhdda74ec2021-01-03 19:30:37 -08001343 TimestampedMessage timestamped_message = state->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -08001344
Austin Schuhe309d2a2019-11-29 13:25:21 -08001345 const monotonic_clock::time_point monotonic_now =
Austin Schuh858c9f32020-08-31 16:56:12 -07001346 state->event_loop()->context().monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001347 if (!FLAGS_skip_order_validation) {
Austin Schuh287d43d2020-12-04 20:19:33 -08001348 CHECK(monotonic_now == timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001349 << ": " << FlatbufferToJson(state->event_loop()->node()) << " Now "
1350 << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001351 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001352 << state->DebugString();
Austin Schuh287d43d2020-12-04 20:19:33 -08001353 } else if (monotonic_now != timestamped_message.monotonic_event_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001354 LOG(WARNING) << "Check failed: monotonic_now == "
Austin Schuh287d43d2020-12-04 20:19:33 -08001355 "timestamped_message.monotonic_event_time) ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001356 << monotonic_now << " vs. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001357 << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001358 << "): " << FlatbufferToJson(state->event_loop()->node())
1359 << " Now " << monotonic_now << " trying to send "
Austin Schuh287d43d2020-12-04 20:19:33 -08001360 << timestamped_message.monotonic_event_time << " failure "
Austin Schuh2f8fd752020-09-01 22:38:28 -07001361 << state->DebugString();
1362 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001363
Austin Schuh287d43d2020-12-04 20:19:33 -08001364 if (timestamped_message.monotonic_event_time >
Austin Schuh858c9f32020-08-31 16:56:12 -07001365 state->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -08001366 event_loop_factory_ != nullptr) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001367 if (timestamped_message.data.span().size() != 0u) {
1368 if (timestamped_message.monotonic_remote_time !=
1369 monotonic_clock::min_time) {
Austin Schuh8bd96322020-02-13 21:18:22 -08001370 // Confirm that the message was sent on the sending node before the
1371 // destination node (this node). As a proxy, do this by making sure
1372 // that time on the source node is past when the message was sent.
Austin Schuh87dd3832021-01-01 23:07:31 -08001373 //
1374 // TODO(austin): <= means that the cause message (which we know) could
1375 // happen after the effect even though we know they are at the same
1376 // time. I doubt anyone will notice for a bit, but we should really
1377 // fix that.
Austin Schuh2f8fd752020-09-01 22:38:28 -07001378 if (!FLAGS_skip_order_validation) {
Austin Schuh87dd3832021-01-01 23:07:31 -08001379 CHECK_LE(
Austin Schuh287d43d2020-12-04 20:19:33 -08001380 timestamped_message.monotonic_remote_time,
1381 state->monotonic_remote_now(timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001382 << state->event_loop()->node()->name()->string_view() << " to "
Austin Schuh287d43d2020-12-04 20:19:33 -08001383 << state->remote_node(timestamped_message.channel_index)
1384 ->name()
1385 ->string_view()
Austin Schuh315b96b2020-12-11 21:21:12 -08001386 << " while trying to send a message on "
1387 << configuration::CleanedChannelToString(
1388 logged_configuration()->channels()->Get(
1389 timestamped_message.channel_index))
Austin Schuh2f8fd752020-09-01 22:38:28 -07001390 << " " << state->DebugString();
Austin Schuh87dd3832021-01-01 23:07:31 -08001391 } else if (timestamped_message.monotonic_remote_time >
Austin Schuh287d43d2020-12-04 20:19:33 -08001392 state->monotonic_remote_now(
1393 timestamped_message.channel_index)) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001394 LOG(WARNING)
Austin Schuh287d43d2020-12-04 20:19:33 -08001395 << "Check failed: timestamped_message.monotonic_remote_time < "
1396 "state->monotonic_remote_now(timestamped_message.channel_"
1397 "index) ("
1398 << timestamped_message.monotonic_remote_time << " vs. "
1399 << state->monotonic_remote_now(
1400 timestamped_message.channel_index)
1401 << ") " << state->event_loop()->node()->name()->string_view()
1402 << " to "
1403 << state->remote_node(timestamped_message.channel_index)
1404 ->name()
1405 ->string_view()
1406 << " currently " << timestamped_message.monotonic_event_time
Austin Schuh2f8fd752020-09-01 22:38:28 -07001407 << " ("
1408 << state->ToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001409 timestamped_message.monotonic_event_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001410 << ") remote event time "
Austin Schuh287d43d2020-12-04 20:19:33 -08001411 << timestamped_message.monotonic_remote_time << " ("
Austin Schuh2f8fd752020-09-01 22:38:28 -07001412 << state->RemoteToDistributedClock(
Austin Schuh287d43d2020-12-04 20:19:33 -08001413 timestamped_message.channel_index,
1414 timestamped_message.monotonic_remote_time)
Austin Schuh2f8fd752020-09-01 22:38:28 -07001415 << ") " << state->DebugString();
1416 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001417 }
1418
Austin Schuh15649d62019-12-28 16:36:38 -08001419 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh287d43d2020-12-04 20:19:33 -08001420 state->SetRealtimeOffset(timestamped_message.monotonic_event_time,
1421 timestamped_message.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -08001422
Austin Schuh2f8fd752020-09-01 22:38:28 -07001423 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Sending "
Austin Schuh287d43d2020-12-04 20:19:33 -08001424 << timestamped_message.monotonic_event_time;
Austin Schuh2f8fd752020-09-01 22:38:28 -07001425 // TODO(austin): std::move channel_data in and make that efficient in
1426 // simulation.
Austin Schuh287d43d2020-12-04 20:19:33 -08001427 state->Send(std::move(timestamped_message));
Austin Schuhdda74ec2021-01-03 19:30:37 -08001428 } else if (!ignore_missing_data_ &&
Austin Schuh5ee56872021-01-30 16:53:34 -08001429 // When starting up, we can have data which was sent before the
1430 // log starts, but the timestamp was after the log starts. This
1431 // is unreasonable to avoid, so ignore the missing data.
1432 timestamped_message.monotonic_remote_time >=
1433 state->monotonic_remote_start_time(
1434 timestamped_message.channel_index) &&
Austin Schuhdda74ec2021-01-03 19:30:37 -08001435 !FLAGS_skip_missing_forwarding_entries) {
Austin Schuh5ee56872021-01-30 16:53:34 -08001436 // We've found a timestamp without data that we expect to have data for.
1437 // This likely means that we are at the end of the log file. Record it
1438 // and CHECK that in the rest of the log file, we don't find any more
1439 // data on that channel. Not all channels will end at the same point in
1440 // time since they can be in different files.
Austin Schuhdda74ec2021-01-03 19:30:37 -08001441 VLOG(1) << "Found the last message on channel "
1442 << timestamped_message.channel_index;
1443
1444 // Vector storing if we've seen a nullptr message or not per channel.
1445 std::vector<bool> last_message;
1446 last_message.resize(logged_configuration()->channels()->size(), false);
1447
1448 last_message[timestamped_message.channel_index] = true;
1449
1450 // Now that we found the end of one channel, artificially stop the
1451 // rest. It is confusing when part of your data gets replayed but not
Austin Schuh5ee56872021-01-30 16:53:34 -08001452 // all. Read the rest of the messages and drop them on the floor while
1453 // doing some basic validation.
Austin Schuh858c9f32020-08-31 16:56:12 -07001454 while (state->OldestMessageTime() != monotonic_clock::max_time) {
Austin Schuhdda74ec2021-01-03 19:30:37 -08001455 TimestampedMessage next = state->PopOldest();
1456 // Make sure that once we have seen the last message on a channel,
1457 // data doesn't start back up again. If the user wants to play
1458 // through events like this, they can set
1459 // --skip_missing_forwarding_entries or ignore_missing_data_.
1460 CHECK_LT(next.channel_index, last_message.size());
1461 if (next.data.span().size() == 0u) {
1462 last_message[next.channel_index] = true;
1463 } else {
1464 if (last_message[next.channel_index]) {
1465 LOG(FATAL)
1466 << "Found missing data in the middle of the log file on "
1467 "channel "
1468 << next.channel_index << " Last "
1469 << last_message[next.channel_index] << state->DebugString();
1470 }
1471 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001472 }
Austin Schuh92547522019-12-28 14:33:43 -08001473 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001474 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001475 LOG(WARNING)
1476 << "Not sending data from before the start of the log file. "
Austin Schuh287d43d2020-12-04 20:19:33 -08001477 << timestamped_message.monotonic_event_time.time_since_epoch().count()
Austin Schuh6f3babe2020-01-26 20:34:50 -08001478 << " start " << monotonic_start_time().time_since_epoch().count()
Austin Schuhd85baf82020-10-19 11:50:12 -07001479 << " "
Austin Schuh287d43d2020-12-04 20:19:33 -08001480 << FlatbufferToJson(timestamped_message.data,
Austin Schuhd85baf82020-10-19 11:50:12 -07001481 {.multi_line = false, .max_vector_size = 100});
Austin Schuhe309d2a2019-11-29 13:25:21 -08001482 }
1483
Austin Schuh858c9f32020-08-31 16:56:12 -07001484 const monotonic_clock::time_point next_time = state->OldestMessageTime();
Austin Schuh6f3babe2020-01-26 20:34:50 -08001485 if (next_time != monotonic_clock::max_time) {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001486 VLOG(1) << "Scheduling " << MaybeNodeName(state->event_loop()->node())
1487 << "wakeup for " << next_time << "("
1488 << state->ToDistributedClock(next_time)
1489 << " distributed), now is " << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001490 state->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -08001491 } else {
Austin Schuh2f8fd752020-09-01 22:38:28 -07001492 VLOG(1) << MaybeNodeName(state->event_loop()->node())
1493 << "No next message, scheduling shutdown";
1494 // Set a timer up immediately after now to die. If we don't do this,
1495 // then the senders waiting on the message we just read will never get
1496 // called.
Austin Schuheecb9282020-01-08 17:43:30 -08001497 if (event_loop_factory_ != nullptr) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001498 state->Setup(monotonic_now + event_loop_factory_->send_delay() +
1499 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -08001500 }
Austin Schuhe309d2a2019-11-29 13:25:21 -08001501 }
Austin Schuh8bd96322020-02-13 21:18:22 -08001502
Austin Schuh2f8fd752020-09-01 22:38:28 -07001503 VLOG(1) << MaybeNodeName(state->event_loop()->node()) << "Done sending at "
1504 << state->event_loop()->context().monotonic_event_time << " now "
1505 << state->monotonic_now();
Austin Schuh858c9f32020-08-31 16:56:12 -07001506 }));
Austin Schuhe309d2a2019-11-29 13:25:21 -08001507
Austin Schuh6f3babe2020-01-26 20:34:50 -08001508 ++live_nodes_;
1509
Austin Schuh858c9f32020-08-31 16:56:12 -07001510 if (state->OldestMessageTime() != monotonic_clock::max_time) {
1511 event_loop->OnRun([state]() { state->Setup(state->OldestMessageTime()); });
Austin Schuhe309d2a2019-11-29 13:25:21 -08001512 }
1513}
1514
1515void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001516 // Make sure that things get destroyed in the correct order, rather than
1517 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -08001518 for (std::unique_ptr<State> &state : states_) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001519 state->Deregister();
Austin Schuhe309d2a2019-11-29 13:25:21 -08001520 }
Austin Schuh92547522019-12-28 14:33:43 -08001521
James Kuszmaul84ff3e52020-01-03 19:48:53 -08001522 event_loop_factory_unique_ptr_.reset();
1523 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -08001524}
1525
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001526void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
Austin Schuh0de30f32020-12-06 12:44:28 -08001527 std::string_view add_prefix,
1528 std::string_view new_type) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001529 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
1530 const Channel *const channel = logged_configuration()->channels()->Get(ii);
1531 if (channel->name()->str() == name &&
1532 channel->type()->string_view() == type) {
1533 CHECK_EQ(0u, remapped_channels_.count(ii))
1534 << "Already remapped channel "
1535 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001536 RemappedChannel remapped_channel;
1537 remapped_channel.remapped_name =
1538 std::string(add_prefix) + std::string(name);
1539 remapped_channel.new_type = new_type;
1540 remapped_channels_[ii] = std::move(remapped_channel);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001541 VLOG(1) << "Remapping channel "
1542 << configuration::CleanedChannelToString(channel)
Austin Schuh0de30f32020-12-06 12:44:28 -08001543 << " to have name " << remapped_channels_[ii].remapped_name;
Austin Schuh6331ef92020-01-07 18:28:09 -08001544 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001545 return;
1546 }
1547 }
1548 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
1549 << type;
1550}
1551
Austin Schuh01b4c352020-09-21 23:09:39 -07001552void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
1553 const Node *node,
Austin Schuh0de30f32020-12-06 12:44:28 -08001554 std::string_view add_prefix,
1555 std::string_view new_type) {
Austin Schuh01b4c352020-09-21 23:09:39 -07001556 VLOG(1) << "Node is " << aos::FlatbufferToJson(node);
1557 const Channel *remapped_channel =
1558 configuration::GetChannel(logged_configuration(), name, type, "", node);
1559 CHECK(remapped_channel != nullptr) << ": Failed to find {\"name\": \"" << name
1560 << "\", \"type\": \"" << type << "\"}";
1561 VLOG(1) << "Original {\"name\": \"" << name << "\", \"type\": \"" << type
1562 << "\"}";
1563 VLOG(1) << "Remapped "
1564 << aos::configuration::StrippedChannelToString(remapped_channel);
1565
1566 // We want to make /spray on node 0 go to /0/spray by snooping the maps. And
1567 // we want it to degrade if the heuristics fail to just work.
1568 //
1569 // The easiest way to do this is going to be incredibly specific and verbose.
1570 // Look up /spray, to /0/spray. Then, prefix the result with /original to get
1571 // /original/0/spray. Then, create a map from /original/spray to
1572 // /original/0/spray for just the type we were asked for.
1573 if (name != remapped_channel->name()->string_view()) {
1574 MapT new_map;
1575 new_map.match = std::make_unique<ChannelT>();
1576 new_map.match->name = absl::StrCat(add_prefix, name);
1577 new_map.match->type = type;
1578 if (node != nullptr) {
1579 new_map.match->source_node = node->name()->str();
1580 }
1581 new_map.rename = std::make_unique<ChannelT>();
1582 new_map.rename->name =
1583 absl::StrCat(add_prefix, remapped_channel->name()->string_view());
1584 maps_.emplace_back(std::move(new_map));
1585 }
1586
1587 const size_t channel_index =
1588 configuration::ChannelIndex(logged_configuration(), remapped_channel);
1589 CHECK_EQ(0u, remapped_channels_.count(channel_index))
1590 << "Already remapped channel "
1591 << configuration::CleanedChannelToString(remapped_channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001592
1593 RemappedChannel remapped_channel_struct;
1594 remapped_channel_struct.remapped_name =
1595 std::string(add_prefix) +
1596 std::string(remapped_channel->name()->string_view());
1597 remapped_channel_struct.new_type = new_type;
1598 remapped_channels_[channel_index] = std::move(remapped_channel_struct);
Austin Schuh01b4c352020-09-21 23:09:39 -07001599 MakeRemappedConfig();
1600}
1601
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001602void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -08001603 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -08001604 if (state) {
Austin Schuh858c9f32020-08-31 16:56:12 -07001605 CHECK(!state->event_loop())
Austin Schuh6aa77be2020-02-22 21:06:40 -08001606 << ": Can't change the mapping after the events are scheduled.";
1607 }
Austin Schuh6f3babe2020-01-26 20:34:50 -08001608 }
Austin Schuhac0771c2020-01-07 18:36:30 -08001609
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001610 // If no remapping occurred and we are using the original config, then there
1611 // is nothing interesting to do here.
1612 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -08001613 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001614 return;
1615 }
1616 // Config to copy Channel definitions from. Use the specified
1617 // replay_configuration_ if it has been provided.
1618 const Configuration *const base_config = replay_configuration_ == nullptr
1619 ? logged_configuration()
1620 : replay_configuration_;
Austin Schuh0de30f32020-12-06 12:44:28 -08001621
1622 // Create a config with all the channels, but un-sorted/merged. Collect up
1623 // the schemas while we do this. Call MergeConfiguration to sort everything,
1624 // and then merge it all in together.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001625
1626 // This is the builder that we use for the config containing all the new
1627 // channels.
Austin Schuh0de30f32020-12-06 12:44:28 -08001628 flatbuffers::FlatBufferBuilder fbb;
1629 fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001630 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001631
1632 CHECK_EQ(Channel::MiniReflectTypeTable()->num_elems, 13u)
1633 << ": Merging logic needs to be updated when the number of channel "
1634 "fields changes.";
1635
1636 // List of schemas.
1637 std::map<std::string_view, FlatbufferVector<reflection::Schema>> schema_map;
1638 // Make sure our new RemoteMessage schema is in there for old logs without it.
1639 schema_map.insert(std::make_pair(
1640 RemoteMessage::GetFullyQualifiedName(),
1641 FlatbufferVector<reflection::Schema>(FlatbufferSpan<reflection::Schema>(
1642 message_bridge::RemoteMessageSchema()))));
1643
1644 // Reconstruct the remapped channels.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001645 for (auto &pair : remapped_channels_) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001646 const Channel *const c = CHECK_NOTNULL(configuration::GetChannel(
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001647 base_config, logged_configuration()->channels()->Get(pair.first), "",
1648 nullptr));
Austin Schuh0de30f32020-12-06 12:44:28 -08001649 channel_offsets.emplace_back(
1650 CopyChannel(c, pair.second.remapped_name, "", &fbb));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001651 }
Austin Schuh01b4c352020-09-21 23:09:39 -07001652
Austin Schuh0de30f32020-12-06 12:44:28 -08001653 // Now reconstruct the original channels, translating types as needed
1654 for (const Channel *c : *base_config->channels()) {
1655 // Search for a mapping channel.
1656 std::string_view new_type = "";
1657 for (auto &pair : remapped_channels_) {
1658 const Channel *const remapped_channel =
1659 logged_configuration()->channels()->Get(pair.first);
1660 if (remapped_channel->name()->string_view() == c->name()->string_view() &&
1661 remapped_channel->type()->string_view() == c->type()->string_view()) {
1662 new_type = pair.second.new_type;
1663 break;
1664 }
1665 }
1666
1667 // Copy everything over.
1668 channel_offsets.emplace_back(CopyChannel(c, "", new_type, &fbb));
1669
1670 // Add the schema if it doesn't exist.
1671 if (schema_map.find(c->type()->string_view()) == schema_map.end()) {
1672 CHECK(c->has_schema());
1673 schema_map.insert(std::make_pair(c->type()->string_view(),
1674 RecursiveCopyFlatBuffer(c->schema())));
1675 }
1676 }
1677
1678 // The MergeConfiguration API takes a vector, not a map. Convert.
1679 std::vector<FlatbufferVector<reflection::Schema>> schemas;
1680 while (!schema_map.empty()) {
1681 schemas.emplace_back(std::move(schema_map.begin()->second));
1682 schema_map.erase(schema_map.begin());
1683 }
1684
1685 // Create the Configuration containing the new channels that we want to add.
1686 const flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Channel>>>
1687 channels_offset =
1688 channel_offsets.empty() ? 0 : fbb.CreateVector(channel_offsets);
1689
1690 // Copy over the old maps.
Austin Schuh01b4c352020-09-21 23:09:39 -07001691 std::vector<flatbuffers::Offset<Map>> map_offsets;
Austin Schuh0de30f32020-12-06 12:44:28 -08001692 if (base_config->maps()) {
1693 for (const Map *map : *base_config->maps()) {
1694 map_offsets.emplace_back(aos::RecursiveCopyFlatBuffer(map, &fbb));
1695 }
1696 }
1697
1698 // Now create the new maps. These are second so they take effect first.
Austin Schuh01b4c352020-09-21 23:09:39 -07001699 for (const MapT &map : maps_) {
1700 const flatbuffers::Offset<flatbuffers::String> match_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001701 fbb.CreateString(map.match->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001702 const flatbuffers::Offset<flatbuffers::String> match_type_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001703 fbb.CreateString(map.match->type);
Austin Schuh01b4c352020-09-21 23:09:39 -07001704 const flatbuffers::Offset<flatbuffers::String> rename_name_offset =
Austin Schuh0de30f32020-12-06 12:44:28 -08001705 fbb.CreateString(map.rename->name);
Austin Schuh01b4c352020-09-21 23:09:39 -07001706 flatbuffers::Offset<flatbuffers::String> match_source_node_offset;
1707 if (!map.match->source_node.empty()) {
Austin Schuh0de30f32020-12-06 12:44:28 -08001708 match_source_node_offset = fbb.CreateString(map.match->source_node);
Austin Schuh01b4c352020-09-21 23:09:39 -07001709 }
Austin Schuh0de30f32020-12-06 12:44:28 -08001710 Channel::Builder match_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001711 match_builder.add_name(match_name_offset);
1712 match_builder.add_type(match_type_offset);
1713 if (!map.match->source_node.empty()) {
1714 match_builder.add_source_node(match_source_node_offset);
1715 }
1716 const flatbuffers::Offset<Channel> match_offset = match_builder.Finish();
1717
Austin Schuh0de30f32020-12-06 12:44:28 -08001718 Channel::Builder rename_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001719 rename_builder.add_name(rename_name_offset);
1720 const flatbuffers::Offset<Channel> rename_offset = rename_builder.Finish();
1721
Austin Schuh0de30f32020-12-06 12:44:28 -08001722 Map::Builder map_builder(fbb);
Austin Schuh01b4c352020-09-21 23:09:39 -07001723 map_builder.add_match(match_offset);
1724 map_builder.add_rename(rename_offset);
1725 map_offsets.emplace_back(map_builder.Finish());
1726 }
1727
Austin Schuh0de30f32020-12-06 12:44:28 -08001728 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Map>>>
1729 maps_offsets = map_offsets.empty() ? 0 : fbb.CreateVector(map_offsets);
Austin Schuh01b4c352020-09-21 23:09:39 -07001730
Austin Schuh0de30f32020-12-06 12:44:28 -08001731 // And copy everything else over.
1732 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Node>>>
1733 nodes_offset = aos::RecursiveCopyVectorTable(base_config->nodes(), &fbb);
1734
1735 flatbuffers::Offset<flatbuffers::Vector<flatbuffers::Offset<Application>>>
1736 applications_offset =
1737 aos::RecursiveCopyVectorTable(base_config->applications(), &fbb);
1738
1739 // Now insert everything else in unmodified.
1740 ConfigurationBuilder configuration_builder(fbb);
1741 if (!channels_offset.IsNull()) {
1742 configuration_builder.add_channels(channels_offset);
1743 }
1744 if (!maps_offsets.IsNull()) {
1745 configuration_builder.add_maps(maps_offsets);
1746 }
1747 if (!nodes_offset.IsNull()) {
1748 configuration_builder.add_nodes(nodes_offset);
1749 }
1750 if (!applications_offset.IsNull()) {
1751 configuration_builder.add_applications(applications_offset);
1752 }
1753
1754 if (base_config->has_channel_storage_duration()) {
1755 configuration_builder.add_channel_storage_duration(
1756 base_config->channel_storage_duration());
1757 }
1758
1759 CHECK_EQ(Configuration::MiniReflectTypeTable()->num_elems, 6u)
1760 << ": Merging logic needs to be updated when the number of configuration "
1761 "fields changes.";
1762
1763 fbb.Finish(configuration_builder.Finish());
1764
1765 // Clean it up and return it! By using MergeConfiguration here, we'll
1766 // actually get a deduplicated config for free too.
1767 FlatbufferDetachedBuffer<Configuration> new_merged_config =
1768 configuration::MergeConfiguration(
1769 FlatbufferDetachedBuffer<Configuration>(fbb.Release()));
1770
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001771 remapped_configuration_buffer_ =
1772 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
Austin Schuh0de30f32020-12-06 12:44:28 -08001773 configuration::MergeConfiguration(new_merged_config, schemas));
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001774
1775 remapped_configuration_ = &remapped_configuration_buffer_->message();
Austin Schuh0de30f32020-12-06 12:44:28 -08001776
1777 // TODO(austin): Lazily re-build to save CPU?
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -08001778}
1779
Austin Schuh6f3babe2020-01-26 20:34:50 -08001780const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
1781 const Channel *channel) {
1782 std::string_view channel_name = channel->name()->string_view();
1783 std::string_view channel_type = channel->type()->string_view();
1784 const int channel_index =
1785 configuration::ChannelIndex(logged_configuration(), channel);
1786 // If the channel is remapped, find the correct channel name to use.
1787 if (remapped_channels_.count(channel_index) > 0) {
Austin Schuhee711052020-08-24 16:06:09 -07001788 VLOG(3) << "Got remapped channel on "
Austin Schuh6f3babe2020-01-26 20:34:50 -08001789 << configuration::CleanedChannelToString(channel);
Austin Schuh0de30f32020-12-06 12:44:28 -08001790 channel_name = remapped_channels_[channel_index].remapped_name;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001791 }
1792
Austin Schuhee711052020-08-24 16:06:09 -07001793 VLOG(2) << "Going to remap channel " << channel_name << " " << channel_type;
Austin Schuh6f3babe2020-01-26 20:34:50 -08001794 const Channel *remapped_channel = configuration::GetChannel(
1795 event_loop->configuration(), channel_name, channel_type,
1796 event_loop->name(), event_loop->node());
1797
1798 CHECK(remapped_channel != nullptr)
1799 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1800 << channel_type << "\"} because it is not in the provided configuration.";
1801
1802 return remapped_channel;
1803}
1804
Austin Schuh287d43d2020-12-04 20:19:33 -08001805LogReader::State::State(std::unique_ptr<TimestampMapper> timestamp_mapper)
1806 : timestamp_mapper_(std::move(timestamp_mapper)) {}
1807
1808void LogReader::State::AddPeer(State *peer) {
1809 if (timestamp_mapper_ && peer->timestamp_mapper_) {
1810 timestamp_mapper_->AddPeer(peer->timestamp_mapper_.get());
1811 }
1812}
Austin Schuh858c9f32020-08-31 16:56:12 -07001813
1814EventLoop *LogReader::State::SetNodeEventLoopFactory(
1815 NodeEventLoopFactory *node_event_loop_factory) {
1816 node_event_loop_factory_ = node_event_loop_factory;
1817 event_loop_unique_ptr_ =
1818 node_event_loop_factory_->MakeEventLoop("log_reader");
1819 return event_loop_unique_ptr_.get();
1820}
1821
1822void LogReader::State::SetChannelCount(size_t count) {
1823 channels_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001824 remote_timestamp_senders_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001825 filters_.resize(count);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001826 channel_source_state_.resize(count);
1827 factory_channel_index_.resize(count);
1828 queue_index_map_.resize(count);
Austin Schuh858c9f32020-08-31 16:56:12 -07001829}
1830
1831void LogReader::State::SetChannel(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001832 size_t logged_channel_index, size_t factory_channel_index,
1833 std::unique_ptr<RawSender> sender,
Austin Schuh2f8fd752020-09-01 22:38:28 -07001834 message_bridge::NoncausalOffsetEstimator *filter,
Austin Schuh969cd602021-01-03 00:09:45 -08001835 RemoteMessageSender *remote_timestamp_sender, State *source_state) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001836 channels_[logged_channel_index] = std::move(sender);
1837 filters_[logged_channel_index] = filter;
1838 remote_timestamp_senders_[logged_channel_index] = remote_timestamp_sender;
1839
1840 if (source_state) {
1841 channel_source_state_[logged_channel_index] = source_state;
1842
1843 if (remote_timestamp_sender != nullptr) {
1844 source_state->queue_index_map_[logged_channel_index] =
Austin Schuh9942bae2021-01-07 22:06:44 -08001845 std::make_unique<std::vector<State::ContiguousSentTimestamp>>();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001846 }
1847 }
1848
1849 factory_channel_index_[logged_channel_index] = factory_channel_index;
1850}
1851
Austin Schuh287d43d2020-12-04 20:19:33 -08001852bool LogReader::State::Send(const TimestampedMessage &timestamped_message) {
1853 aos::RawSender *sender = channels_[timestamped_message.channel_index].get();
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001854 uint32_t remote_queue_index = 0xffffffff;
1855
Austin Schuh287d43d2020-12-04 20:19:33 -08001856 if (remote_timestamp_senders_[timestamped_message.channel_index] != nullptr) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001857 std::vector<ContiguousSentTimestamp> *queue_index_map = CHECK_NOTNULL(
Austin Schuh287d43d2020-12-04 20:19:33 -08001858 CHECK_NOTNULL(channel_source_state_[timestamped_message.channel_index])
1859 ->queue_index_map_[timestamped_message.channel_index]
1860 .get());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001861
Austin Schuh9942bae2021-01-07 22:06:44 -08001862 struct SentTimestamp {
1863 monotonic_clock::time_point monotonic_event_time;
1864 uint32_t queue_index;
1865 } search;
1866
Austin Schuh287d43d2020-12-04 20:19:33 -08001867 search.monotonic_event_time = timestamped_message.monotonic_remote_time;
Austin Schuh287d43d2020-12-04 20:19:33 -08001868 search.queue_index = timestamped_message.remote_queue_index;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001869
1870 // Find the sent time if available.
1871 auto element = std::lower_bound(
1872 queue_index_map->begin(), queue_index_map->end(), search,
Austin Schuh9942bae2021-01-07 22:06:44 -08001873 [](ContiguousSentTimestamp a, SentTimestamp b) {
1874 if (a.ending_monotonic_event_time < b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001875 return true;
1876 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001877 if (a.starting_monotonic_event_time > b.monotonic_event_time) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001878 return false;
1879 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001880
1881 if (a.ending_queue_index < b.queue_index) {
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001882 return true;
1883 }
Austin Schuh9942bae2021-01-07 22:06:44 -08001884 if (a.starting_queue_index >= b.queue_index) {
1885 return false;
1886 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001887
Austin Schuh9942bae2021-01-07 22:06:44 -08001888 // If it isn't clearly below or above, it is below. Since we return
1889 // the last element <, this will return a match.
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001890 return false;
1891 });
1892
1893 // TODO(austin): Be a bit more principled here, but we will want to do that
1894 // after the logger rewrite. We hit this when one node finishes, but the
1895 // other node isn't done yet. So there is no send time, but there is a
1896 // receive time.
1897 if (element != queue_index_map->end()) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001898 CHECK_GE(timestamped_message.monotonic_remote_time,
1899 element->starting_monotonic_event_time);
1900 CHECK_LE(timestamped_message.monotonic_remote_time,
1901 element->ending_monotonic_event_time);
1902 CHECK_GE(timestamped_message.remote_queue_index,
1903 element->starting_queue_index);
1904 CHECK_LE(timestamped_message.remote_queue_index,
1905 element->ending_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001906
Austin Schuh9942bae2021-01-07 22:06:44 -08001907 remote_queue_index = timestamped_message.remote_queue_index +
1908 element->actual_queue_index -
1909 element->starting_queue_index;
1910 } else {
1911 VLOG(1) << "No timestamp match in the map.";
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001912 }
1913 }
1914
1915 // Send! Use the replayed queue index here instead of the logged queue index
1916 // for the remote queue index. This makes re-logging work.
Austin Schuh287d43d2020-12-04 20:19:33 -08001917 const bool sent = sender->Send(
1918 timestamped_message.data.message().data()->Data(),
1919 timestamped_message.data.message().data()->size(),
1920 timestamped_message.monotonic_remote_time,
1921 timestamped_message.realtime_remote_time, remote_queue_index);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001922 if (!sent) return false;
1923
Austin Schuh287d43d2020-12-04 20:19:33 -08001924 if (queue_index_map_[timestamped_message.channel_index]) {
Austin Schuh9942bae2021-01-07 22:06:44 -08001925 if (queue_index_map_[timestamped_message.channel_index]->empty()) {
1926 // Nothing here, start a range with 0 length.
1927 ContiguousSentTimestamp timestamp;
1928 timestamp.starting_monotonic_event_time =
1929 timestamp.ending_monotonic_event_time =
1930 timestamped_message.monotonic_event_time;
1931 timestamp.starting_queue_index = timestamp.ending_queue_index =
1932 timestamped_message.queue_index;
1933 timestamp.actual_queue_index = sender->sent_queue_index();
1934 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1935 timestamp);
1936 } else {
1937 // We've got something. See if the next timestamp is still contiguous. If
1938 // so, grow it.
1939 ContiguousSentTimestamp *back =
1940 &queue_index_map_[timestamped_message.channel_index]->back();
1941 if ((back->starting_queue_index - back->actual_queue_index) ==
1942 (timestamped_message.queue_index - sender->sent_queue_index())) {
1943 back->ending_queue_index = timestamped_message.queue_index;
1944 back->ending_monotonic_event_time =
1945 timestamped_message.monotonic_event_time;
1946 } else {
1947 // Otherwise, make a new one.
1948 ContiguousSentTimestamp timestamp;
1949 timestamp.starting_monotonic_event_time =
1950 timestamp.ending_monotonic_event_time =
1951 timestamped_message.monotonic_event_time;
1952 timestamp.starting_queue_index = timestamp.ending_queue_index =
1953 timestamped_message.queue_index;
1954 timestamp.actual_queue_index = sender->sent_queue_index();
1955 queue_index_map_[timestamped_message.channel_index]->emplace_back(
1956 timestamp);
1957 }
1958 }
1959
1960 // TODO(austin): Should we prune the map? On a many day log, I only saw the
1961 // queue index diverge a couple of elements, which would be a very small
1962 // map.
Austin Schuh287d43d2020-12-04 20:19:33 -08001963 } else if (remote_timestamp_senders_[timestamped_message.channel_index] !=
1964 nullptr) {
Austin Schuh969cd602021-01-03 00:09:45 -08001965 flatbuffers::FlatBufferBuilder fbb;
1966 fbb.ForceDefaults(true);
Austin Schuh315b96b2020-12-11 21:21:12 -08001967 flatbuffers::Offset<flatbuffers::String> boot_uuid_offset =
Austin Schuh969cd602021-01-03 00:09:45 -08001968 fbb.CreateString(event_loop_->boot_uuid().string_view());
Austin Schuh315b96b2020-12-11 21:21:12 -08001969
Austin Schuh969cd602021-01-03 00:09:45 -08001970 RemoteMessage::Builder message_header_builder(fbb);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001971
1972 message_header_builder.add_channel_index(
Austin Schuh287d43d2020-12-04 20:19:33 -08001973 factory_channel_index_[timestamped_message.channel_index]);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001974
1975 // Swap the remote and sent metrics. They are from the sender's
1976 // perspective, not the receiver's perspective.
1977 message_header_builder.add_monotonic_sent_time(
1978 sender->monotonic_sent_time().time_since_epoch().count());
1979 message_header_builder.add_realtime_sent_time(
1980 sender->realtime_sent_time().time_since_epoch().count());
1981 message_header_builder.add_queue_index(sender->sent_queue_index());
1982
1983 message_header_builder.add_monotonic_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001984 timestamped_message.monotonic_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001985 message_header_builder.add_realtime_remote_time(
Austin Schuh287d43d2020-12-04 20:19:33 -08001986 timestamped_message.realtime_remote_time.time_since_epoch().count());
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001987
1988 message_header_builder.add_remote_queue_index(remote_queue_index);
Austin Schuh315b96b2020-12-11 21:21:12 -08001989 message_header_builder.add_boot_uuid(boot_uuid_offset);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001990
Austin Schuh969cd602021-01-03 00:09:45 -08001991 fbb.Finish(message_header_builder.Finish());
1992
1993 remote_timestamp_senders_[timestamped_message.channel_index]->Send(
1994 FlatbufferDetachedBuffer<RemoteMessage>(fbb.Release()),
1995 timestamped_message.monotonic_timestamp_time);
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07001996 }
1997
1998 return true;
1999}
2000
Austin Schuh969cd602021-01-03 00:09:45 -08002001LogReader::RemoteMessageSender::RemoteMessageSender(
2002 aos::Sender<message_bridge::RemoteMessage> sender, EventLoop *event_loop)
2003 : event_loop_(event_loop),
2004 sender_(std::move(sender)),
2005 timer_(event_loop->AddTimer([this]() { SendTimestamp(); })) {}
2006
2007void LogReader::RemoteMessageSender::ScheduleTimestamp() {
2008 if (remote_timestamps_.empty()) {
2009 CHECK_NOTNULL(timer_);
2010 timer_->Disable();
2011 scheduled_time_ = monotonic_clock::min_time;
2012 return;
2013 }
2014
2015 if (scheduled_time_ != remote_timestamps_.front().monotonic_timestamp_time) {
2016 CHECK_NOTNULL(timer_);
Austin Schuh816e5d62021-01-05 23:42:20 -08002017 timer_->Setup(remote_timestamps_.front().monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002018 scheduled_time_ = remote_timestamps_.front().monotonic_timestamp_time;
2019 }
2020}
2021
2022void LogReader::RemoteMessageSender::Send(
2023 FlatbufferDetachedBuffer<RemoteMessage> remote_message,
2024 monotonic_clock::time_point monotonic_timestamp_time) {
2025 // There are 2 cases. Either we have a monotonic_timestamp_time and need to
2026 // resend the timestamp at the correct time, or we don't and can send it
2027 // immediately.
2028 if (monotonic_timestamp_time == monotonic_clock::min_time) {
2029 CHECK(remote_timestamps_.empty())
2030 << ": Unsupported mix of timestamps and no timestamps.";
2031 sender_.Send(std::move(remote_message));
2032 } else {
Austin Schuhb22ae422021-01-31 17:57:06 -08002033 remote_timestamps_.emplace(
2034 std::upper_bound(
2035 remote_timestamps_.begin(), remote_timestamps_.end(),
2036 monotonic_timestamp_time,
2037 [](const aos::monotonic_clock::time_point monotonic_timestamp_time,
2038 const Timestamp &timestamp) {
2039 return monotonic_timestamp_time <
2040 timestamp.monotonic_timestamp_time;
2041 }),
2042 std::move(remote_message), monotonic_timestamp_time);
Austin Schuh969cd602021-01-03 00:09:45 -08002043 ScheduleTimestamp();
2044 }
2045}
2046
2047void LogReader::RemoteMessageSender::SendTimestamp() {
2048 CHECK_EQ(event_loop_->context().monotonic_event_time, scheduled_time_);
2049 CHECK(!remote_timestamps_.empty());
2050
2051 // Send out all timestamps at the currently scheduled time.
2052 while (remote_timestamps_.front().monotonic_timestamp_time ==
2053 scheduled_time_) {
2054 sender_.Send(std::move(remote_timestamps_.front().remote_message));
2055 remote_timestamps_.pop_front();
2056 if (remote_timestamps_.empty()) {
2057 break;
2058 }
2059 }
2060 scheduled_time_ = monotonic_clock::min_time;
2061
2062 ScheduleTimestamp();
2063}
2064
2065LogReader::RemoteMessageSender *LogReader::State::RemoteTimestampSender(
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002066 const Node *delivered_node) {
2067 auto sender = remote_timestamp_senders_map_.find(delivered_node);
2068
2069 if (sender == remote_timestamp_senders_map_.end()) {
Austin Schuh969cd602021-01-03 00:09:45 -08002070 sender =
2071 remote_timestamp_senders_map_
2072 .emplace(delivered_node,
2073 std::make_unique<RemoteMessageSender>(
2074 event_loop()->MakeSender<RemoteMessage>(absl::StrCat(
2075 "/aos/remote_timestamps/",
2076 delivered_node->name()->string_view())),
2077 event_loop()))
2078 .first;
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002079 }
2080
Austin Schuh969cd602021-01-03 00:09:45 -08002081 return sender->second.get();
Austin Schuh858c9f32020-08-31 16:56:12 -07002082}
2083
Austin Schuhdda74ec2021-01-03 19:30:37 -08002084TimestampedMessage LogReader::State::PopOldest() {
Austin Schuhe639ea12021-01-25 13:00:22 -08002085 CHECK(timestamp_mapper_ != nullptr);
2086 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2087 CHECK(result_ptr != nullptr);
Austin Schuh858c9f32020-08-31 16:56:12 -07002088
Austin Schuhe639ea12021-01-25 13:00:22 -08002089 TimestampedMessage result = std::move(*result_ptr);
2090
Austin Schuh2f8fd752020-09-01 22:38:28 -07002091 VLOG(2) << MaybeNodeName(event_loop_->node()) << "PopOldest Popping "
Austin Schuhe639ea12021-01-25 13:00:22 -08002092 << result.monotonic_event_time;
2093 timestamp_mapper_->PopFront();
Austin Schuh858c9f32020-08-31 16:56:12 -07002094 SeedSortedMessages();
2095
Austin Schuhe639ea12021-01-25 13:00:22 -08002096 if (result.monotonic_remote_time != monotonic_clock::min_time) {
2097 message_bridge::NoncausalOffsetEstimator *filter =
2098 filters_[result.channel_index];
2099 CHECK(filter != nullptr);
2100
2101 // TODO(austin): We probably want to push this down into the timestamp
2102 // mapper directly.
2103 filter->Pop(event_loop_->node(), result.monotonic_event_time);
Austin Schuh2f8fd752020-09-01 22:38:28 -07002104 }
Austin Schuh5ee56872021-01-30 16:53:34 -08002105 VLOG(1) << "Popped " << result
2106 << configuration::CleanedChannelToString(
2107 event_loop_->configuration()->channels()->Get(
2108 factory_channel_index_[result.channel_index]));
Austin Schuhe639ea12021-01-25 13:00:22 -08002109 return result;
Austin Schuh858c9f32020-08-31 16:56:12 -07002110}
2111
2112monotonic_clock::time_point LogReader::State::OldestMessageTime() const {
Austin Schuhe639ea12021-01-25 13:00:22 -08002113 if (timestamp_mapper_ == nullptr) {
Austin Schuh287d43d2020-12-04 20:19:33 -08002114 return monotonic_clock::max_time;
2115 }
Austin Schuhe639ea12021-01-25 13:00:22 -08002116 TimestampedMessage *result_ptr = timestamp_mapper_->Front();
2117 if (result_ptr == nullptr) {
2118 return monotonic_clock::max_time;
2119 }
2120 VLOG(2) << MaybeNodeName(event_loop_->node()) << "oldest message at "
2121 << result_ptr->monotonic_event_time;
2122 return result_ptr->monotonic_event_time;
Austin Schuh858c9f32020-08-31 16:56:12 -07002123}
2124
2125void LogReader::State::SeedSortedMessages() {
Austin Schuh287d43d2020-12-04 20:19:33 -08002126 if (!timestamp_mapper_) return;
Austin Schuh858c9f32020-08-31 16:56:12 -07002127
Austin Schuhe639ea12021-01-25 13:00:22 -08002128 timestamp_mapper_->QueueFor(chrono::duration_cast<chrono::seconds>(
2129 chrono::duration<double>(FLAGS_time_estimation_buffer_seconds)));
Austin Schuh858c9f32020-08-31 16:56:12 -07002130}
2131
2132void LogReader::State::Deregister() {
2133 for (size_t i = 0; i < channels_.size(); ++i) {
2134 channels_[i].reset();
2135 }
Austin Schuh8d7e0bb2020-10-02 17:57:00 -07002136 remote_timestamp_senders_map_.clear();
Austin Schuh858c9f32020-08-31 16:56:12 -07002137 event_loop_unique_ptr_.reset();
2138 event_loop_ = nullptr;
2139 timer_handler_ = nullptr;
2140 node_event_loop_factory_ = nullptr;
2141}
2142
Austin Schuhe309d2a2019-11-29 13:25:21 -08002143} // namespace logger
2144} // namespace aos