blob: b3472d75ee788709822769257f34496ab757b06e [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
Austin Schuh4c4e0092019-12-22 16:18:03 -08004#include <limits.h>
Austin Schuhe309d2a2019-11-29 13:25:21 -08005#include <sys/stat.h>
6#include <sys/types.h>
7#include <sys/uio.h>
8#include <vector>
9
Austin Schuh8bd96322020-02-13 21:18:22 -080010#include "Eigen/Dense"
Austin Schuhe309d2a2019-11-29 13:25:21 -080011#include "absl/types/span.h"
12#include "aos/events/event_loop.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080013#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080014#include "aos/flatbuffer_merge.h"
Austin Schuh288479d2019-12-18 19:47:52 -080015#include "aos/network/team_number.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080016#include "aos/time/time.h"
17#include "flatbuffers/flatbuffers.h"
18
Austin Schuh15649d62019-12-28 16:36:38 -080019DEFINE_bool(skip_missing_forwarding_entries, false,
20 "If true, drop any forwarding entries with missing data. If "
21 "false, CHECK.");
Austin Schuhe309d2a2019-11-29 13:25:21 -080022
Austin Schuh8bd96322020-02-13 21:18:22 -080023DEFINE_bool(timestamps_to_csv, false,
24 "If true, write all the time synchronization information to a set "
25 "of CSV files in /tmp/. This should only be needed when debugging "
26 "time synchronization.");
27
Austin Schuhe309d2a2019-11-29 13:25:21 -080028namespace aos {
29namespace logger {
30
31namespace chrono = std::chrono;
32
Austin Schuhe309d2a2019-11-29 13:25:21 -080033Logger::Logger(DetachedBufferWriter *writer, EventLoop *event_loop,
34 std::chrono::milliseconds polling_period)
Austin Schuh6f3babe2020-01-26 20:34:50 -080035 : Logger(std::make_unique<LocalLogNamer>(writer, event_loop->node()),
36 event_loop, polling_period) {}
37
38Logger::Logger(std::unique_ptr<LogNamer> log_namer, EventLoop *event_loop,
39 std::chrono::milliseconds polling_period)
Austin Schuhe309d2a2019-11-29 13:25:21 -080040 : event_loop_(event_loop),
Austin Schuh6f3babe2020-01-26 20:34:50 -080041 log_namer_(std::move(log_namer)),
Austin Schuhe309d2a2019-11-29 13:25:21 -080042 timer_handler_(event_loop_->AddTimer([this]() { DoLogData(); })),
43 polling_period_(polling_period) {
Austin Schuh6f3babe2020-01-26 20:34:50 -080044 VLOG(1) << "Starting logger for " << FlatbufferToJson(event_loop_->node());
45 int channel_index = 0;
Austin Schuhe309d2a2019-11-29 13:25:21 -080046 for (const Channel *channel : *event_loop_->configuration()->channels()) {
47 FetcherStruct fs;
Austin Schuh6f3babe2020-01-26 20:34:50 -080048 const bool is_local =
49 configuration::ChannelIsSendableOnNode(channel, event_loop_->node());
50
Austin Schuh15649d62019-12-28 16:36:38 -080051 const bool is_readable =
52 configuration::ChannelIsReadableOnNode(channel, event_loop_->node());
53 const bool log_message = configuration::ChannelMessageIsLoggedOnNode(
54 channel, event_loop_->node()) &&
55 is_readable;
56
57 const bool log_delivery_times =
58 (event_loop_->node() == nullptr)
59 ? false
60 : configuration::ConnectionDeliveryTimeIsLoggedOnNode(
61 channel, event_loop_->node(), event_loop_->node());
62
63 if (log_message || log_delivery_times) {
64 fs.fetcher = event_loop->MakeRawFetcher(channel);
65 VLOG(1) << "Logging channel "
66 << configuration::CleanedChannelToString(channel);
67
68 if (log_delivery_times) {
Austin Schuh6f3babe2020-01-26 20:34:50 -080069 VLOG(1) << " Delivery times";
70 fs.timestamp_writer = log_namer_->MakeTimestampWriter(channel);
Austin Schuh15649d62019-12-28 16:36:38 -080071 }
Austin Schuh6f3babe2020-01-26 20:34:50 -080072 if (log_message) {
73 VLOG(1) << " Data";
74 fs.writer = log_namer_->MakeWriter(channel);
75 if (!is_local) {
76 fs.log_type = LogType::kLogRemoteMessage;
77 }
78 }
79 fs.channel_index = channel_index;
80 fs.written = false;
81 fetchers_.emplace_back(std::move(fs));
Austin Schuh15649d62019-12-28 16:36:38 -080082 }
Austin Schuh6f3babe2020-01-26 20:34:50 -080083 ++channel_index;
Austin Schuhe309d2a2019-11-29 13:25:21 -080084 }
85
86 // When things start, we want to log the header, then the most recent messages
87 // available on each fetcher to capture the previous state, then start
88 // polling.
89 event_loop_->OnRun([this, polling_period]() {
90 // Grab data from each channel right before we declare the log file started
91 // so we can capture the latest message on each channel. This lets us have
92 // non periodic messages with configuration that now get logged.
93 for (FetcherStruct &f : fetchers_) {
Austin Schuh6f3babe2020-01-26 20:34:50 -080094 f.written = !f.fetcher->Fetch();
Austin Schuhe309d2a2019-11-29 13:25:21 -080095 }
96
97 // We need to pick a point in time to declare the log file "started". This
98 // starts here. It needs to be after everything is fetched so that the
99 // fetchers are all pointed at the most recent message before the start
100 // time.
Austin Schuhfa895892020-01-07 20:07:41 -0800101 monotonic_start_time_ = event_loop_->monotonic_now();
102 realtime_start_time_ = event_loop_->realtime_now();
103 last_synchronized_time_ = monotonic_start_time_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800104
Austin Schuhcde938c2020-02-02 17:30:07 -0800105 LOG(INFO) << "Logging node as " << FlatbufferToJson(event_loop_->node())
106 << " start_time " << monotonic_start_time_;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800107
Austin Schuhfa895892020-01-07 20:07:41 -0800108 WriteHeader();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800109
110 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period,
111 polling_period);
112 });
113}
114
Austin Schuhcde938c2020-02-02 17:30:07 -0800115// TODO(austin): Set the remote start time to the first time we see a remote
116// message when we are logging those messages separate? Need to signal what to
117// do, or how to get a good timestamp.
Austin Schuhfa895892020-01-07 20:07:41 -0800118void Logger::WriteHeader() {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800119 for (const Node *node : log_namer_->nodes()) {
120 WriteHeader(node);
121 }
122}
Austin Schuh8bd96322020-02-13 21:18:22 -0800123
Austin Schuh6f3babe2020-01-26 20:34:50 -0800124void Logger::WriteHeader(const Node *node) {
Austin Schuhfa895892020-01-07 20:07:41 -0800125 // Now write the header with this timestamp in it.
126 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800127 fbb.ForceDefaults(true);
Austin Schuhfa895892020-01-07 20:07:41 -0800128
129 flatbuffers::Offset<aos::Configuration> configuration_offset =
130 CopyFlatBuffer(event_loop_->configuration(), &fbb);
131
132 flatbuffers::Offset<flatbuffers::String> string_offset =
133 fbb.CreateString(network::GetHostname());
134
135 flatbuffers::Offset<Node> node_offset;
136 if (event_loop_->node() != nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800137 node_offset = CopyFlatBuffer(node, &fbb);
Austin Schuhfa895892020-01-07 20:07:41 -0800138 }
139
140 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
141
142 log_file_header_builder.add_name(string_offset);
143
144 // Only add the node if we are running in a multinode configuration.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800145 if (node != nullptr) {
Austin Schuhfa895892020-01-07 20:07:41 -0800146 log_file_header_builder.add_node(node_offset);
147 }
148
149 log_file_header_builder.add_configuration(configuration_offset);
150 // The worst case theoretical out of order is the polling period times 2.
151 // One message could get logged right after the boundary, but be for right
152 // before the next boundary. And the reverse could happen for another
153 // message. Report back 3x to be extra safe, and because the cost isn't
154 // huge on the read side.
155 log_file_header_builder.add_max_out_of_order_duration(
156 std::chrono::duration_cast<std::chrono::nanoseconds>(3 * polling_period_)
157 .count());
158
159 log_file_header_builder.add_monotonic_start_time(
160 std::chrono::duration_cast<std::chrono::nanoseconds>(
161 monotonic_start_time_.time_since_epoch())
162 .count());
163 log_file_header_builder.add_realtime_start_time(
164 std::chrono::duration_cast<std::chrono::nanoseconds>(
165 realtime_start_time_.time_since_epoch())
166 .count());
167
168 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800169 log_namer_->WriteHeader(&fbb, node);
Austin Schuhfa895892020-01-07 20:07:41 -0800170}
171
172void Logger::Rotate(DetachedBufferWriter *writer) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800173 Rotate(std::make_unique<LocalLogNamer>(writer, event_loop_->node()));
174}
175
176void Logger::Rotate(std::unique_ptr<LogNamer> log_namer) {
Austin Schuhfa895892020-01-07 20:07:41 -0800177 // Force data up until now to be written.
178 DoLogData();
179
180 // Swap the writer out, and re-write the header.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800181 log_namer_ = std::move(log_namer);
182
183 // And then update the writers.
184 for (FetcherStruct &f : fetchers_) {
185 const Channel *channel =
186 event_loop_->configuration()->channels()->Get(f.channel_index);
187 if (f.timestamp_writer != nullptr) {
188 f.timestamp_writer = log_namer_->MakeTimestampWriter(channel);
189 }
190 if (f.writer != nullptr) {
191 f.writer = log_namer_->MakeWriter(channel);
192 }
193 }
194
Austin Schuhfa895892020-01-07 20:07:41 -0800195 WriteHeader();
196}
197
Austin Schuhe309d2a2019-11-29 13:25:21 -0800198void Logger::DoLogData() {
199 // We want to guarentee that messages aren't out of order by more than
200 // max_out_of_order_duration. To do this, we need sync points. Every write
201 // cycle should be a sync point.
Austin Schuhfa895892020-01-07 20:07:41 -0800202 const monotonic_clock::time_point monotonic_now =
203 event_loop_->monotonic_now();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800204
205 do {
206 // Move the sync point up by at most polling_period. This forces one sync
207 // per iteration, even if it is small.
208 last_synchronized_time_ =
209 std::min(last_synchronized_time_ + polling_period_, monotonic_now);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800210 // Write each channel to disk, one at a time.
211 for (FetcherStruct &f : fetchers_) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800212 while (true) {
213 if (f.written) {
214 if (!f.fetcher->FetchNext()) {
215 VLOG(2) << "No new data on "
216 << configuration::CleanedChannelToString(
217 f.fetcher->channel());
218 break;
219 } else {
220 f.written = false;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800221 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800222 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800223
Austin Schuh6f3babe2020-01-26 20:34:50 -0800224 CHECK(!f.written);
Austin Schuh15649d62019-12-28 16:36:38 -0800225
Austin Schuh6f3babe2020-01-26 20:34:50 -0800226 // TODO(james): Write tests to exercise this logic.
227 if (f.fetcher->context().monotonic_event_time <
228 last_synchronized_time_) {
229 if (f.writer != nullptr) {
Austin Schuh15649d62019-12-28 16:36:38 -0800230 // Write!
231 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
232 max_header_size_);
Austin Schuhd7b15da2020-02-17 15:06:11 -0800233 fbb.ForceDefaults(true);
Austin Schuh15649d62019-12-28 16:36:38 -0800234
235 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236 f.channel_index, f.log_type));
Austin Schuh15649d62019-12-28 16:36:38 -0800237
Austin Schuhcde938c2020-02-02 17:30:07 -0800238 VLOG(2) << "Writing data as node "
Austin Schuh6f3babe2020-01-26 20:34:50 -0800239 << FlatbufferToJson(event_loop_->node()) << " for channel "
Austin Schuh15649d62019-12-28 16:36:38 -0800240 << configuration::CleanedChannelToString(
Austin Schuh6f3babe2020-01-26 20:34:50 -0800241 f.fetcher->channel())
Austin Schuhcde938c2020-02-02 17:30:07 -0800242 << " to " << f.writer->filename() << " data "
Austin Schuh6f3babe2020-01-26 20:34:50 -0800243 << FlatbufferToJson(
244 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
245 fbb.GetBufferPointer()));
Austin Schuh15649d62019-12-28 16:36:38 -0800246
247 max_header_size_ = std::max(
248 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800249 f.writer->QueueSizedFlatbuffer(&fbb);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800250 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800251
252 if (f.timestamp_writer != nullptr) {
253 // And now handle timestamps.
254 flatbuffers::FlatBufferBuilder fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800255 fbb.ForceDefaults(true);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800256
257 fbb.FinishSizePrefixed(PackMessage(&fbb, f.fetcher->context(),
258 f.channel_index,
259 LogType::kLogDeliveryTimeOnly));
260
Austin Schuhcde938c2020-02-02 17:30:07 -0800261 VLOG(2) << "Writing timestamps as node "
Austin Schuh6f3babe2020-01-26 20:34:50 -0800262 << FlatbufferToJson(event_loop_->node()) << " for channel "
263 << configuration::CleanedChannelToString(
264 f.fetcher->channel())
Austin Schuhcde938c2020-02-02 17:30:07 -0800265 << " to " << f.timestamp_writer->filename() << " timestamp "
Austin Schuh6f3babe2020-01-26 20:34:50 -0800266 << FlatbufferToJson(
267 flatbuffers::GetSizePrefixedRoot<MessageHeader>(
268 fbb.GetBufferPointer()));
269
270 f.timestamp_writer->QueueSizedFlatbuffer(&fbb);
271 }
272
273 f.written = true;
274 } else {
275 break;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800276 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800277 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800278 }
279
Austin Schuhe309d2a2019-11-29 13:25:21 -0800280 // If we missed cycles, we could be pretty far behind. Spin until we are
281 // caught up.
282 } while (last_synchronized_time_ + polling_period_ < monotonic_now);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800283}
284
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800285LogReader::LogReader(std::string_view filename,
286 const Configuration *replay_configuration)
Austin Schuhfa895892020-01-07 20:07:41 -0800287 : LogReader(std::vector<std::string>{std::string(filename)},
288 replay_configuration) {}
289
290LogReader::LogReader(const std::vector<std::string> &filenames,
291 const Configuration *replay_configuration)
Austin Schuh6f3babe2020-01-26 20:34:50 -0800292 : LogReader(std::vector<std::vector<std::string>>{filenames},
293 replay_configuration) {}
294
295LogReader::LogReader(const std::vector<std::vector<std::string>> &filenames,
296 const Configuration *replay_configuration)
297 : filenames_(filenames),
298 log_file_header_(ReadHeader(filenames[0][0])),
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800299 replay_configuration_(replay_configuration) {
Austin Schuh6331ef92020-01-07 18:28:09 -0800300 MakeRemappedConfig();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800301
Austin Schuh6aa77be2020-02-22 21:06:40 -0800302 if (replay_configuration) {
303 CHECK_EQ(configuration::MultiNode(configuration()),
304 configuration::MultiNode(replay_configuration))
305 << ": Log file and replay config need to both be multi or single node.";
306 }
307
Austin Schuh6f3babe2020-01-26 20:34:50 -0800308 if (!configuration::MultiNode(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800309 states_.emplace_back(std::make_unique<State>());
310 State *state = states_[0].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800311
312 state->channel_merger = std::make_unique<ChannelMerger>(filenames);
Austin Schuh8bd96322020-02-13 21:18:22 -0800313 } else {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800314 if (replay_configuration) {
James Kuszmaul46d82582020-05-09 19:50:09 -0700315 CHECK_EQ(logged_configuration()->nodes()->size(),
Austin Schuh6aa77be2020-02-22 21:06:40 -0800316 replay_configuration->nodes()->size())
317 << ": Log file and replay config need to have matching nodes lists.";
James Kuszmaul46d82582020-05-09 19:50:09 -0700318 for (const Node *node : *logged_configuration()->nodes()) {
319 if (configuration::GetNode(replay_configuration, node) == nullptr) {
320 LOG(FATAL)
321 << "Found node " << FlatbufferToJson(node)
322 << " in logged config that is not present in the replay config.";
323 }
324 }
Austin Schuh6aa77be2020-02-22 21:06:40 -0800325 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800326 states_.resize(configuration()->nodes()->size());
Austin Schuh6f3babe2020-01-26 20:34:50 -0800327 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800328}
329
Austin Schuh6aa77be2020-02-22 21:06:40 -0800330LogReader::~LogReader() {
331 Deregister();
Austin Schuh8bd96322020-02-13 21:18:22 -0800332 if (offset_fp_ != nullptr) {
333 fclose(offset_fp_);
334 }
335}
Austin Schuhe309d2a2019-11-29 13:25:21 -0800336
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800337const Configuration *LogReader::logged_configuration() const {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800338 return log_file_header_.message().configuration();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800339}
340
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800341const Configuration *LogReader::configuration() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800342 return remapped_configuration_;
343}
344
Austin Schuh6f3babe2020-01-26 20:34:50 -0800345std::vector<const Node *> LogReader::Nodes() const {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800346 // Because the Node pointer will only be valid if it actually points to memory
347 // owned by remapped_configuration_, we need to wait for the
348 // remapped_configuration_ to be populated before accessing it.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800349 //
350 // Also, note, that when ever a map is changed, the nodes in here are
351 // invalidated.
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800352 CHECK(remapped_configuration_ != nullptr)
353 << ": Need to call Register before the node() pointer will be valid.";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800354 return configuration::GetNodes(remapped_configuration_);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800355}
Austin Schuh15649d62019-12-28 16:36:38 -0800356
Austin Schuh6f3babe2020-01-26 20:34:50 -0800357monotonic_clock::time_point LogReader::monotonic_start_time(const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800358 State *state =
359 states_[configuration::GetNodeIndex(configuration(), node)].get();
360 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
361
362 return state->channel_merger->monotonic_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800363}
364
Austin Schuh6f3babe2020-01-26 20:34:50 -0800365realtime_clock::time_point LogReader::realtime_start_time(const Node *node) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800366 State *state =
367 states_[configuration::GetNodeIndex(configuration(), node)].get();
368 CHECK(state != nullptr) << ": Unknown node " << FlatbufferToJson(node);
369
370 return state->channel_merger->realtime_start_time();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800371}
372
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800373void LogReader::Register() {
374 event_loop_factory_unique_ptr_ =
Austin Schuhac0771c2020-01-07 18:36:30 -0800375 std::make_unique<SimulatedEventLoopFactory>(configuration());
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800376 Register(event_loop_factory_unique_ptr_.get());
377}
378
Austin Schuh92547522019-12-28 14:33:43 -0800379void LogReader::Register(SimulatedEventLoopFactory *event_loop_factory) {
Austin Schuh92547522019-12-28 14:33:43 -0800380 event_loop_factory_ = event_loop_factory;
Austin Schuh92547522019-12-28 14:33:43 -0800381
Austin Schuh6f3babe2020-01-26 20:34:50 -0800382 for (const Node *node : configuration::GetNodes(configuration())) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800383 const size_t node_index =
384 configuration::GetNodeIndex(configuration(), node);
385 states_[node_index] = std::make_unique<State>();
386 State *state = states_[node_index].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800387
388 state->channel_merger = std::make_unique<ChannelMerger>(filenames_);
389
390 state->node_event_loop_factory =
391 event_loop_factory_->GetNodeEventLoopFactory(node);
392 state->event_loop_unique_ptr =
393 event_loop_factory->MakeEventLoop("log_reader", node);
394
395 Register(state->event_loop_unique_ptr.get());
Austin Schuhcde938c2020-02-02 17:30:07 -0800396 }
James Kuszmaul46d82582020-05-09 19:50:09 -0700397 if (live_nodes_ == 0) {
398 LOG(FATAL)
399 << "Don't have logs from any of the nodes in the replay config--are "
400 "you sure that the replay config matches the original config?";
401 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800402
Austin Schuh8bd96322020-02-13 21:18:22 -0800403 // We need to now seed our per-node time offsets and get everything set up to
404 // run.
405 const size_t num_nodes = !configuration::MultiNode(logged_configuration())
406 ? 1u
407 : logged_configuration()->nodes()->size();
Austin Schuhcde938c2020-02-02 17:30:07 -0800408
Austin Schuh8bd96322020-02-13 21:18:22 -0800409 // It is easiest to solve for per node offsets with a matrix rather than
410 // trying to solve the equations by hand. So let's get after it.
411 //
412 // Now, build up the map matrix.
413 //
414 // sample_matrix_ = map_matrix_ * offset_matrix_
415 map_matrix_ = Eigen::MatrixXd::Zero(filters_.size() + 1, num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800416
Austin Schuh8bd96322020-02-13 21:18:22 -0800417 sample_matrix_ = Eigen::VectorXd::Zero(filters_.size() + 1);
418 offset_matrix_ = Eigen::VectorXd::Zero(num_nodes);
Austin Schuhcde938c2020-02-02 17:30:07 -0800419
Austin Schuh8bd96322020-02-13 21:18:22 -0800420 // And the base offset matrix, which will be a copy of the initial offset
421 // matrix.
422 base_offset_matrix_ =
423 Eigen::Matrix<std::chrono::nanoseconds, Eigen::Dynamic, 1>::Zero(
424 num_nodes);
425
426 // All offsets should sum to 0. Add that as the first constraint in our least
427 // squares.
428 map_matrix_.row(0).setOnes();
429
430 {
431 // Now, add the a - b -> sample elements.
432 size_t i = 1;
433 for (std::pair<const std::tuple<const Node *, const Node *>,
434 message_bridge::ClippedAverageFilter> &filter : filters_) {
435 const Node *const node_a = std::get<0>(filter.first);
436 const Node *const node_b = std::get<1>(filter.first);
437
438 const size_t node_a_index =
439 configuration::GetNodeIndex(configuration(), node_a);
440 const size_t node_b_index =
441 configuration::GetNodeIndex(configuration(), node_b);
442
443 // +a
444 map_matrix_(i, node_a_index) = 1.0;
445 // -b
446 map_matrix_(i, node_b_index) = -1.0;
447
448 // -> sample
449 filter.second.set_sample_pointer(&sample_matrix_(i, 0));
450
451 ++i;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800452 }
453 }
454
Austin Schuh8bd96322020-02-13 21:18:22 -0800455 // Rank of the map matrix tells you if all the nodes are in communication with
456 // each other, which tells you if the offsets are observable.
457 const size_t connected_nodes =
458 Eigen::FullPivLU<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>(
459 map_matrix_)
460 .rank();
461
462 // We don't need to support isolated nodes until someone has a real use case.
463 CHECK_EQ(connected_nodes, num_nodes)
464 << ": There is a node which isn't communicating with the rest.";
465
466 // Now, iterate through all the timestamps from all the nodes and seed
467 // everything.
468 for (std::unique_ptr<State> &state : states_) {
469 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
470 TimestampMerger::DeliveryTimestamp timestamp =
471 state->channel_merger->OldestTimestampForChannel(i);
472 if (timestamp.monotonic_event_time != monotonic_clock::min_time) {
473 CHECK(state->MaybeUpdateTimestamp(timestamp, i));
474 }
475 }
476 }
477
478 // Make sure all the samples have been seeded.
479 for (int i = 1; i < sample_matrix_.cols(); ++i) {
480 // The seeding logic is pretty basic right now because we don't have great
481 // use cases yet. It wants to see data from every node. Blow up for now,
482 // and once we have a reason to do something different, update this logic.
483 // Maybe read further in the log file? Or seed off the realtime time?
484 CHECK_NE(sample_matrix_(i, 0), 0.0)
485 << ": Sample " << i << " is not seeded.";
486 }
487
488 // And solve.
489 offset_matrix_ = SolveOffsets();
490
491 // Save off the base offsets so we can work in deltas from here out. That
492 // will significantly simplify the numerical precision problems.
493 for (size_t i = 0; i < num_nodes; ++i) {
494 base_offset_matrix_(i, 0) =
495 std::chrono::duration_cast<std::chrono::nanoseconds>(
496 std::chrono::duration<double>(offset_matrix_(i, 0)));
497 }
498
499 {
500 // Shift everything so we never could (reasonably) require the distributed
501 // clock to have a large backwards jump in time. This makes it so the boot
502 // time on the node up the longest will essentially start matching the
503 // distributed clock.
504 const chrono::nanoseconds offset = -base_offset_matrix_.maxCoeff();
505 for (int i = 0; i < base_offset_matrix_.rows(); ++i) {
506 base_offset_matrix_(i, 0) += offset;
507 }
508 }
509
510 {
511 // Re-compute the samples and setup all the filters so that they
512 // subtract this base offset.
513
514 size_t i = 1;
515 for (std::pair<const std::tuple<const Node *, const Node *>,
516 message_bridge::ClippedAverageFilter> &filter : filters_) {
517 CHECK(filter.second.sample_pointer() == &sample_matrix_(i, 0));
518
519 const Node *const node_a = std::get<0>(filter.first);
520 const Node *const node_b = std::get<1>(filter.first);
521
522 const size_t node_a_index =
523 configuration::GetNodeIndex(configuration(), node_a);
524 const size_t node_b_index =
525 configuration::GetNodeIndex(configuration(), node_b);
526
527 filter.second.set_base_offset(base_offset_matrix_(node_a_index) -
528 base_offset_matrix_(node_b_index));
529
530 ++i;
531 }
532 }
533
534 // Now, iterate again through all the offsets now that we have set the base
535 // offset to something sane. This will seed everything with an accurate
536 // initial offset.
537 for (std::unique_ptr<State> &state : states_) {
538 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
539 TimestampMerger::DeliveryTimestamp timestamp =
540 state->channel_merger->OldestTimestampForChannel(i);
541 if (timestamp.monotonic_event_time != monotonic_clock::min_time) {
542 CHECK(state->MaybeUpdateTimestamp(timestamp, i));
543 }
544 }
545 }
546
547 UpdateOffsets();
548
Austin Schuhcde938c2020-02-02 17:30:07 -0800549 // We want to start the log file at the last start time of the log files from
550 // all the nodes. Compute how long each node's simulation needs to run to
551 // move time to this point.
Austin Schuh8bd96322020-02-13 21:18:22 -0800552 distributed_clock::time_point start_time = distributed_clock::min_time;
Austin Schuhcde938c2020-02-02 17:30:07 -0800553
Austin Schuh8bd96322020-02-13 21:18:22 -0800554 for (std::unique_ptr<State> &state : states_) {
555 // Setup the realtime clock to have something sane in it now.
Austin Schuhcde938c2020-02-02 17:30:07 -0800556 state->node_event_loop_factory->SetRealtimeOffset(
557 state->channel_merger->monotonic_start_time(),
558 state->channel_merger->realtime_start_time());
Austin Schuh8bd96322020-02-13 21:18:22 -0800559 // And start computing the start time on the distributed clock now that that
560 // works.
561 start_time = std::max(start_time,
562 state->node_event_loop_factory->ToDistributedClock(
563 state->channel_merger->monotonic_start_time()));
Austin Schuhcde938c2020-02-02 17:30:07 -0800564 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800565 CHECK_GE(start_time, distributed_clock::epoch());
Austin Schuhcde938c2020-02-02 17:30:07 -0800566
Austin Schuh6f3babe2020-01-26 20:34:50 -0800567 // Forwarding is tracked per channel. If it is enabled, we want to turn it
568 // off. Otherwise messages replayed will get forwarded across to the other
569 // nodes, and also replayed on the other nodes. This may not satisfy all our
570 // users, but it'll start the discussion.
571 if (configuration::MultiNode(event_loop_factory_->configuration())) {
572 for (size_t i = 0; i < logged_configuration()->channels()->size(); ++i) {
573 const Channel *channel = logged_configuration()->channels()->Get(i);
574 const Node *node = configuration::GetNode(
575 configuration(), channel->source_node()->string_view());
576
Austin Schuh8bd96322020-02-13 21:18:22 -0800577 State *state =
578 states_[configuration::GetNodeIndex(configuration(), node)].get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800579
580 const Channel *remapped_channel =
581 RemapChannel(state->event_loop, channel);
582
583 event_loop_factory_->DisableForwarding(remapped_channel);
584 }
585 }
586
Austin Schuhcde938c2020-02-02 17:30:07 -0800587 // While we are starting the system up, we might be relying on matching data
588 // to timestamps on log files where the timestamp log file starts before the
589 // data. In this case, it is reasonable to expect missing data.
590 ignore_missing_data_ = true;
Austin Schuh8bd96322020-02-13 21:18:22 -0800591 event_loop_factory_->RunFor(start_time.time_since_epoch());
Austin Schuhcde938c2020-02-02 17:30:07 -0800592 // Now that we are running for real, missing data means that the log file is
593 // corrupted or went wrong.
594 ignore_missing_data_ = false;
Austin Schuh92547522019-12-28 14:33:43 -0800595}
596
Austin Schuh8bd96322020-02-13 21:18:22 -0800597void LogReader::UpdateOffsets() {
598 // TODO(austin): Evaluate less accurate inverses. We might be able to
599 // do some tricks to keep the accuracy up.
600 offset_matrix_ = SolveOffsets();
601
602 size_t node_index = 0;
603 for (std::unique_ptr<State> &state : states_) {
604 state->node_event_loop_factory->SetDistributedOffset(offset(node_index));
605 ++node_index;
606 }
607}
608
609std::tuple<message_bridge::ClippedAverageFilter *, bool> LogReader::GetFilter(
610 const Node *node_a, const Node *node_b) {
611 CHECK_NE(node_a, node_b);
612 CHECK_EQ(configuration::GetNode(configuration(), node_a), node_a);
613 CHECK_EQ(configuration::GetNode(configuration(), node_b), node_b);
614
615 if (node_a > node_b) {
616 return std::make_pair(std::get<0>(GetFilter(node_b, node_a)), false);
617 }
618
619 auto tuple = std::make_tuple(node_a, node_b);
620
621 auto it = filters_.find(tuple);
622
623 if (it == filters_.end()) {
624 auto &x = filters_
625 .insert(std::make_pair(
626 tuple, message_bridge::ClippedAverageFilter()))
627 .first->second;
628 if (FLAGS_timestamps_to_csv) {
629 std::string fwd_name =
630 absl::StrCat("/tmp/timestamp_", node_a->name()->string_view(), "_",
631 node_b->name()->string_view(), ".csv");
632 x.fwd_fp = fopen(fwd_name.c_str(), "w");
633 std::string rev_name =
634 absl::StrCat("/tmp/timestamp_", node_b->name()->string_view(), "_",
635 node_a->name()->string_view(), ".csv");
636 x.rev_fp = fopen(rev_name.c_str(), "w");
637 }
638
639 return std::make_tuple(&x, true);
640 } else {
641 return std::make_tuple(&(it->second), true);
642 }
643}
644
645bool LogReader::State::MaybeUpdateTimestamp(
646 const TimestampMerger::DeliveryTimestamp &channel_timestamp,
647 int channel_index) {
648 if (channel_timestamp.monotonic_remote_time == monotonic_clock::min_time) {
649 return false;
650 }
651
652 // Got a forwarding timestamp!
653 CHECK(std::get<0>(filters[channel_index]) != nullptr);
654
655 // Call the correct method depending on if we are the forward or reverse
656 // direction here.
657 if (std::get<1>(filters[channel_index])) {
658 std::get<0>(filters[channel_index])
659 ->FwdSample(channel_timestamp.monotonic_event_time,
660 channel_timestamp.monotonic_event_time -
661 channel_timestamp.monotonic_remote_time);
662 } else {
663 std::get<0>(filters[channel_index])
664 ->RevSample(channel_timestamp.monotonic_event_time,
665 channel_timestamp.monotonic_event_time -
666 channel_timestamp.monotonic_remote_time);
667 }
668 return true;
669}
670
Austin Schuhe309d2a2019-11-29 13:25:21 -0800671void LogReader::Register(EventLoop *event_loop) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800672 State *state =
673 states_[configuration::GetNodeIndex(configuration(), event_loop->node())]
674 .get();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800675
676 state->event_loop = event_loop;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800677
Tyler Chatow67ddb032020-01-12 14:30:04 -0800678 // We don't run timing reports when trying to print out logged data, because
679 // otherwise we would end up printing out the timing reports themselves...
680 // This is only really relevant when we are replaying into a simulation.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800681 event_loop->SkipTimingReport();
682 event_loop->SkipAosLog();
Austin Schuh39788ff2019-12-01 18:22:57 -0800683
Austin Schuh6aa77be2020-02-22 21:06:40 -0800684 const bool has_data = state->channel_merger->SetNode(event_loop->node());
Austin Schuhe309d2a2019-11-29 13:25:21 -0800685
Austin Schuh6f3babe2020-01-26 20:34:50 -0800686 state->channels.resize(logged_configuration()->channels()->size());
Austin Schuh8bd96322020-02-13 21:18:22 -0800687 state->filters.resize(state->channels.size());
688
689 state->channel_target_event_loop_factory.resize(state->channels.size());
Austin Schuh6331ef92020-01-07 18:28:09 -0800690
Austin Schuh6f3babe2020-01-26 20:34:50 -0800691 for (size_t i = 0; i < state->channels.size(); ++i) {
692 const Channel *channel =
693 RemapChannel(event_loop, logged_configuration()->channels()->Get(i));
Austin Schuh6331ef92020-01-07 18:28:09 -0800694
Austin Schuh6f3babe2020-01-26 20:34:50 -0800695 state->channels[i] = event_loop->MakeRawSender(channel);
Austin Schuh8bd96322020-02-13 21:18:22 -0800696
697 state->filters[i] = std::make_tuple(nullptr, false);
698
699 if (!configuration::ChannelIsSendableOnNode(channel, event_loop->node()) &&
700 configuration::ChannelIsReadableOnNode(channel, event_loop->node())) {
701 const Node *target_node = configuration::GetNode(
702 event_loop->configuration(), channel->source_node()->string_view());
703 state->filters[i] = GetFilter(event_loop->node(), target_node);
704
705 if (event_loop_factory_ != nullptr) {
706 state->channel_target_event_loop_factory[i] =
707 event_loop_factory_->GetNodeEventLoopFactory(target_node);
708 }
709 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800710 }
711
Austin Schuh6aa77be2020-02-22 21:06:40 -0800712 // If we didn't find any log files with data in them, we won't ever get a
713 // callback or be live. So skip the rest of the setup.
714 if (!has_data) {
715 return;
716 }
717
Austin Schuh6f3babe2020-01-26 20:34:50 -0800718 state->timer_handler = event_loop->AddTimer([this, state]() {
719 if (state->channel_merger->OldestMessage() == monotonic_clock::max_time) {
720 --live_nodes_;
Austin Schuh6aa77be2020-02-22 21:06:40 -0800721 VLOG(1) << "Node down!";
Austin Schuh6f3babe2020-01-26 20:34:50 -0800722 if (live_nodes_ == 0) {
723 event_loop_factory_->Exit();
724 }
James Kuszmaul314f1672020-01-03 20:02:08 -0800725 return;
726 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800727 bool update_offsets = false;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800728 TimestampMerger::DeliveryTimestamp channel_timestamp;
Austin Schuh05b70472020-01-01 17:11:17 -0800729 int channel_index;
730 FlatbufferVector<MessageHeader> channel_data =
731 FlatbufferVector<MessageHeader>::Empty();
732
733 std::tie(channel_timestamp, channel_index, channel_data) =
Austin Schuh6f3babe2020-01-26 20:34:50 -0800734 state->channel_merger->PopOldest();
Austin Schuh05b70472020-01-01 17:11:17 -0800735
Austin Schuhe309d2a2019-11-29 13:25:21 -0800736 const monotonic_clock::time_point monotonic_now =
Austin Schuh6f3babe2020-01-26 20:34:50 -0800737 state->event_loop->context().monotonic_event_time;
738 CHECK(monotonic_now == channel_timestamp.monotonic_event_time)
Austin Schuh8bd96322020-02-13 21:18:22 -0800739 << ": " << FlatbufferToJson(state->event_loop->node()) << " Now "
740 << monotonic_now << " trying to send "
741 << channel_timestamp.monotonic_event_time << " failure "
742 << state->channel_merger->DebugString();
Austin Schuhe309d2a2019-11-29 13:25:21 -0800743
Austin Schuh6f3babe2020-01-26 20:34:50 -0800744 if (channel_timestamp.monotonic_event_time >
745 state->channel_merger->monotonic_start_time() ||
Austin Schuh15649d62019-12-28 16:36:38 -0800746 event_loop_factory_ != nullptr) {
Austin Schuh8bd96322020-02-13 21:18:22 -0800747 if ((!ignore_missing_data_ && !FLAGS_skip_missing_forwarding_entries &&
748 !state->channel_merger->at_end()) ||
Austin Schuh05b70472020-01-01 17:11:17 -0800749 channel_data.message().data() != nullptr) {
750 CHECK(channel_data.message().data() != nullptr)
751 << ": Got a message without data. Forwarding entry which was "
Austin Schuh6f3babe2020-01-26 20:34:50 -0800752 "not matched? Use --skip_missing_forwarding_entries to ignore "
Austin Schuh15649d62019-12-28 16:36:38 -0800753 "this.";
Austin Schuh92547522019-12-28 14:33:43 -0800754
Austin Schuh8bd96322020-02-13 21:18:22 -0800755 if (state->MaybeUpdateTimestamp(channel_timestamp, channel_index)) {
756 // Confirm that the message was sent on the sending node before the
757 // destination node (this node). As a proxy, do this by making sure
758 // that time on the source node is past when the message was sent.
759 CHECK_LT(channel_timestamp.monotonic_remote_time,
760 state->channel_target_event_loop_factory[channel_index]
761 ->monotonic_now());
762
763 update_offsets = true;
764
765 if (FLAGS_timestamps_to_csv) {
766 if (offset_fp_ == nullptr) {
767 offset_fp_ = fopen("/tmp/offsets.csv", "w");
768 fprintf(
769 offset_fp_,
770 "# time_since_start, offset node 0, offset node 1, ...\n");
771 first_time_ = channel_timestamp.realtime_event_time;
772 }
773
774 fprintf(offset_fp_, "%.9f",
775 std::chrono::duration_cast<std::chrono::duration<double>>(
776 channel_timestamp.realtime_event_time - first_time_)
777 .count());
778 for (int i = 0; i < base_offset_matrix_.rows(); ++i) {
779 fprintf(
780 offset_fp_, ", %.9f",
781 offset_matrix_(i, 0) +
782 std::chrono::duration_cast<std::chrono::duration<double>>(
783 base_offset_matrix_(i, 0))
784 .count());
785 }
786 fprintf(offset_fp_, "\n");
787 }
788
789 } else {
790 CHECK(std::get<0>(state->filters[channel_index]) == nullptr);
791 }
792
Austin Schuh15649d62019-12-28 16:36:38 -0800793 // If we have access to the factory, use it to fix the realtime time.
Austin Schuh6f3babe2020-01-26 20:34:50 -0800794 if (state->node_event_loop_factory != nullptr) {
795 state->node_event_loop_factory->SetRealtimeOffset(
796 channel_timestamp.monotonic_event_time,
797 channel_timestamp.realtime_event_time);
Austin Schuh15649d62019-12-28 16:36:38 -0800798 }
799
Austin Schuh6f3babe2020-01-26 20:34:50 -0800800 state->channels[channel_index]->Send(
Austin Schuh05b70472020-01-01 17:11:17 -0800801 channel_data.message().data()->Data(),
802 channel_data.message().data()->size(),
Austin Schuh6f3babe2020-01-26 20:34:50 -0800803 channel_timestamp.monotonic_remote_time,
804 channel_timestamp.realtime_remote_time,
805 channel_timestamp.remote_queue_index);
Austin Schuh8bd96322020-02-13 21:18:22 -0800806 } else if (state->channel_merger->at_end()) {
807 // We are at the end of the log file and found missing data. Finish
808 // reading the rest of the log file and call it quits. We don't want to
809 // replay partial data.
810 while (state->channel_merger->OldestMessage() !=
811 monotonic_clock::max_time) {
812 state->channel_merger->PopOldest();
813 }
Austin Schuh92547522019-12-28 14:33:43 -0800814 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800815
Austin Schuhe309d2a2019-11-29 13:25:21 -0800816 } else {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800817 LOG(WARNING)
818 << "Not sending data from before the start of the log file. "
819 << channel_timestamp.monotonic_event_time.time_since_epoch().count()
820 << " start " << monotonic_start_time().time_since_epoch().count()
821 << " " << FlatbufferToJson(channel_data);
Austin Schuhe309d2a2019-11-29 13:25:21 -0800822 }
823
Austin Schuh6f3babe2020-01-26 20:34:50 -0800824 const monotonic_clock::time_point next_time =
825 state->channel_merger->OldestMessage();
826 if (next_time != monotonic_clock::max_time) {
827 state->timer_handler->Setup(next_time);
James Kuszmaul314f1672020-01-03 20:02:08 -0800828 } else {
829 // Set a timer up immediately after now to die. If we don't do this, then
830 // the senders waiting on the message we just read will never get called.
Austin Schuheecb9282020-01-08 17:43:30 -0800831 if (event_loop_factory_ != nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800832 state->timer_handler->Setup(monotonic_now +
833 event_loop_factory_->send_delay() +
834 std::chrono::nanoseconds(1));
Austin Schuheecb9282020-01-08 17:43:30 -0800835 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800836 }
Austin Schuh8bd96322020-02-13 21:18:22 -0800837
838 // Once we make this call, the current time changes. So do everything which
839 // involves time before changing it. That especially includes sending the
840 // message.
841 if (update_offsets) {
842 UpdateOffsets();
843 }
Austin Schuhe309d2a2019-11-29 13:25:21 -0800844 });
845
Austin Schuh6f3babe2020-01-26 20:34:50 -0800846 ++live_nodes_;
847
848 if (state->channel_merger->OldestMessage() != monotonic_clock::max_time) {
849 event_loop->OnRun([state]() {
850 state->timer_handler->Setup(state->channel_merger->OldestMessage());
Austin Schuh05b70472020-01-01 17:11:17 -0800851 });
Austin Schuhe309d2a2019-11-29 13:25:21 -0800852 }
853}
854
855void LogReader::Deregister() {
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800856 // Make sure that things get destroyed in the correct order, rather than
857 // relying on getting the order correct in the class definition.
Austin Schuh8bd96322020-02-13 21:18:22 -0800858 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800859 for (size_t i = 0; i < state->channels.size(); ++i) {
860 state->channels[i].reset();
861 }
862 state->event_loop_unique_ptr.reset();
863 state->event_loop = nullptr;
864 state->node_event_loop_factory = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800865 }
Austin Schuh92547522019-12-28 14:33:43 -0800866
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800867 event_loop_factory_unique_ptr_.reset();
868 event_loop_factory_ = nullptr;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800869}
870
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800871void LogReader::RemapLoggedChannel(std::string_view name, std::string_view type,
872 std::string_view add_prefix) {
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800873 for (size_t ii = 0; ii < logged_configuration()->channels()->size(); ++ii) {
874 const Channel *const channel = logged_configuration()->channels()->Get(ii);
875 if (channel->name()->str() == name &&
876 channel->type()->string_view() == type) {
877 CHECK_EQ(0u, remapped_channels_.count(ii))
878 << "Already remapped channel "
879 << configuration::CleanedChannelToString(channel);
880 remapped_channels_[ii] = std::string(add_prefix) + std::string(name);
881 VLOG(1) << "Remapping channel "
882 << configuration::CleanedChannelToString(channel)
883 << " to have name " << remapped_channels_[ii];
Austin Schuh6331ef92020-01-07 18:28:09 -0800884 MakeRemappedConfig();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800885 return;
886 }
887 }
888 LOG(FATAL) << "Unabled to locate channel with name " << name << " and type "
889 << type;
890}
891
892void LogReader::MakeRemappedConfig() {
Austin Schuh8bd96322020-02-13 21:18:22 -0800893 for (std::unique_ptr<State> &state : states_) {
Austin Schuh6aa77be2020-02-22 21:06:40 -0800894 if (state) {
895 CHECK(!state->event_loop)
896 << ": Can't change the mapping after the events are scheduled.";
897 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800898 }
Austin Schuhac0771c2020-01-07 18:36:30 -0800899
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800900 // If no remapping occurred and we are using the original config, then there
901 // is nothing interesting to do here.
902 if (remapped_channels_.empty() && replay_configuration_ == nullptr) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800903 remapped_configuration_ = logged_configuration();
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800904 return;
905 }
906 // Config to copy Channel definitions from. Use the specified
907 // replay_configuration_ if it has been provided.
908 const Configuration *const base_config = replay_configuration_ == nullptr
909 ? logged_configuration()
910 : replay_configuration_;
911 // The remapped config will be identical to the base_config, except that it
912 // will have a bunch of extra channels in the channel list, which are exact
913 // copies of the remapped channels, but with different names.
914 // Because the flatbuffers API is a pain to work with, this requires a bit of
915 // a song-and-dance to get copied over.
916 // The order of operations is to:
917 // 1) Make a flatbuffer builder for a config that will just contain a list of
918 // the new channels that we want to add.
919 // 2) For each channel that we are remapping:
920 // a) Make a buffer/builder and construct into it a Channel table that only
921 // contains the new name for the channel.
922 // b) Merge the new channel with just the name into the channel that we are
923 // trying to copy, built in the flatbuffer builder made in 1. This gives
924 // us the new channel definition that we need.
925 // 3) Using this list of offsets, build the Configuration of just new
926 // Channels.
927 // 4) Merge the Configuration with the new Channels into the base_config.
928 // 5) Call MergeConfiguration() on that result to give MergeConfiguration a
929 // chance to sanitize the config.
930
931 // This is the builder that we use for the config containing all the new
932 // channels.
933 flatbuffers::FlatBufferBuilder new_config_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800934 new_config_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800935 std::vector<flatbuffers::Offset<Channel>> channel_offsets;
936 for (auto &pair : remapped_channels_) {
937 // This is the builder that we use for creating the Channel with just the
938 // new name.
939 flatbuffers::FlatBufferBuilder new_name_fbb;
Austin Schuhd7b15da2020-02-17 15:06:11 -0800940 new_name_fbb.ForceDefaults(true);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800941 const flatbuffers::Offset<flatbuffers::String> name_offset =
942 new_name_fbb.CreateString(pair.second);
943 ChannelBuilder new_name_builder(new_name_fbb);
944 new_name_builder.add_name(name_offset);
945 new_name_fbb.Finish(new_name_builder.Finish());
946 const FlatbufferDetachedBuffer<Channel> new_name = new_name_fbb.Release();
947 // Retrieve the channel that we want to copy, confirming that it is actually
948 // present in base_config.
949 const Channel *const base_channel = CHECK_NOTNULL(configuration::GetChannel(
950 base_config, logged_configuration()->channels()->Get(pair.first), "",
951 nullptr));
952 // Actually create the new channel and put it into the vector of Offsets
953 // that we will use to create the new Configuration.
954 channel_offsets.emplace_back(MergeFlatBuffers<Channel>(
955 reinterpret_cast<const flatbuffers::Table *>(base_channel),
956 reinterpret_cast<const flatbuffers::Table *>(&new_name.message()),
957 &new_config_fbb));
958 }
959 // Create the Configuration containing the new channels that we want to add.
Austin Schuhfa895892020-01-07 20:07:41 -0800960 const auto new_name_vector_offsets =
961 new_config_fbb.CreateVector(channel_offsets);
James Kuszmaulc7bbb3e2020-01-03 20:01:00 -0800962 ConfigurationBuilder new_config_builder(new_config_fbb);
963 new_config_builder.add_channels(new_name_vector_offsets);
964 new_config_fbb.Finish(new_config_builder.Finish());
965 const FlatbufferDetachedBuffer<Configuration> new_name_config =
966 new_config_fbb.Release();
967 // Merge the new channels configuration into the base_config, giving us the
968 // remapped configuration.
969 remapped_configuration_buffer_ =
970 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
971 MergeFlatBuffers<Configuration>(base_config,
972 &new_name_config.message()));
973 // Call MergeConfiguration to deal with sanitizing the config.
974 remapped_configuration_buffer_ =
975 std::make_unique<FlatbufferDetachedBuffer<Configuration>>(
976 configuration::MergeConfiguration(*remapped_configuration_buffer_));
977
978 remapped_configuration_ = &remapped_configuration_buffer_->message();
979}
980
Austin Schuh6f3babe2020-01-26 20:34:50 -0800981const Channel *LogReader::RemapChannel(const EventLoop *event_loop,
982 const Channel *channel) {
983 std::string_view channel_name = channel->name()->string_view();
984 std::string_view channel_type = channel->type()->string_view();
985 const int channel_index =
986 configuration::ChannelIndex(logged_configuration(), channel);
987 // If the channel is remapped, find the correct channel name to use.
988 if (remapped_channels_.count(channel_index) > 0) {
989 VLOG(2) << "Got remapped channel on "
990 << configuration::CleanedChannelToString(channel);
991 channel_name = remapped_channels_[channel_index];
992 }
993
994 VLOG(1) << "Going to remap channel " << channel_name << " " << channel_type;
995 const Channel *remapped_channel = configuration::GetChannel(
996 event_loop->configuration(), channel_name, channel_type,
997 event_loop->name(), event_loop->node());
998
999 CHECK(remapped_channel != nullptr)
1000 << ": Unable to send {\"name\": \"" << channel_name << "\", \"type\": \""
1001 << channel_type << "\"} because it is not in the provided configuration.";
1002
1003 return remapped_channel;
1004}
1005
Austin Schuhe309d2a2019-11-29 13:25:21 -08001006} // namespace logger
1007} // namespace aos