blob: 686e0a8eed7a7d40a41dadebd86ca01bdd422db8 [file] [log] [blame]
Austin Schuha36c8902019-12-30 18:07:15 -08001#include "aos/events/logging/logfile_utils.h"
2
3#include <fcntl.h>
Austin Schuha36c8902019-12-30 18:07:15 -08004#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
7
Brian Silvermanf51499a2020-09-21 12:49:08 -07008#include <algorithm>
9#include <climits>
Austin Schuha36c8902019-12-30 18:07:15 -080010
Austin Schuhe4fca832020-03-07 16:58:53 -080011#include "absl/strings/escaping.h"
Austin Schuh05b70472020-01-01 17:11:17 -080012#include "aos/configuration.h"
Austin Schuhfa895892020-01-07 20:07:41 -080013#include "aos/flatbuffer_merge.h"
Austin Schuh6f3babe2020-01-26 20:34:50 -080014#include "aos/util/file.h"
Austin Schuha36c8902019-12-30 18:07:15 -080015#include "flatbuffers/flatbuffers.h"
Austin Schuh05b70472020-01-01 17:11:17 -080016#include "gflags/gflags.h"
17#include "glog/logging.h"
Austin Schuha36c8902019-12-30 18:07:15 -080018
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070019#if defined(__x86_64__)
20#define ENABLE_LZMA 1
21#elif defined(__aarch64__)
22#define ENABLE_LZMA 1
23#else
24#define ENABLE_LZMA 0
25#endif
26
27#if ENABLE_LZMA
28#include "aos/events/logging/lzma_encoder.h"
29#endif
30
Austin Schuh7fbf5a72020-09-21 16:28:13 -070031DEFINE_int32(flush_size, 128000,
Austin Schuha36c8902019-12-30 18:07:15 -080032 "Number of outstanding bytes to allow before flushing to disk.");
33
Austin Schuha040c3f2021-02-13 16:09:07 -080034DEFINE_double(
35 max_out_of_order, -1,
36 "If set, this overrides the max out of order duration for a log file.");
37
Brian Silvermanf51499a2020-09-21 12:49:08 -070038namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080039
Austin Schuh05b70472020-01-01 17:11:17 -080040namespace chrono = std::chrono;
41
Brian Silvermanf51499a2020-09-21 12:49:08 -070042DetachedBufferWriter::DetachedBufferWriter(
43 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
44 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070045 if (!util::MkdirPIfSpace(filename, 0777)) {
46 ran_out_of_space_ = true;
47 } else {
48 fd_ = open(std::string(filename).c_str(),
49 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
50 if (fd_ == -1 && errno == ENOSPC) {
51 ran_out_of_space_ = true;
52 } else {
53 PCHECK(fd_ != -1) << ": Failed to open " << filename << " for writing";
54 VLOG(1) << "Opened " << filename << " for writing";
55 }
56 }
Austin Schuha36c8902019-12-30 18:07:15 -080057}
58
59DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070060 Close();
61 if (ran_out_of_space_) {
62 CHECK(acknowledge_ran_out_of_space_)
63 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070064 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070065}
66
Brian Silvermand90905f2020-09-23 14:42:56 -070067DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070068 *this = std::move(other);
69}
70
Brian Silverman87ac0402020-09-17 14:47:01 -070071// When other is destroyed "soon" (which it should be because we're getting an
72// rvalue reference to it), it will flush etc all the data we have queued up
73// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -070074DetachedBufferWriter &DetachedBufferWriter::operator=(
75 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070076 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070077 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070078 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -070079 std::swap(ran_out_of_space_, other.ran_out_of_space_);
80 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070081 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070082 std::swap(max_write_time_, other.max_write_time_);
83 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
84 std::swap(max_write_time_messages_, other.max_write_time_messages_);
85 std::swap(total_write_time_, other.total_write_time_);
86 std::swap(total_write_count_, other.total_write_count_);
87 std::swap(total_write_messages_, other.total_write_messages_);
88 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070089 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -080090}
91
Brian Silvermanf51499a2020-09-21 12:49:08 -070092void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070093 if (ran_out_of_space_) {
94 // We don't want any later data to be written after space becomes
95 // available, so refuse to write anything more once we've dropped data
96 // because we ran out of space.
97 VLOG(1) << "Ignoring span: " << span.size();
98 return;
99 }
100
Brian Silvermanf51499a2020-09-21 12:49:08 -0700101 if (encoder_->may_bypass() && span.size() > 4096u) {
102 // Over this threshold, we'll assume it's cheaper to add an extra
103 // syscall to write the data immediately instead of copying it to
104 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800105
Brian Silvermanf51499a2020-09-21 12:49:08 -0700106 // First, flush everything.
107 while (encoder_->queue_size() > 0u) {
108 Flush();
109 }
Austin Schuhde031b72020-01-10 19:34:41 -0800110
Brian Silvermanf51499a2020-09-21 12:49:08 -0700111 // Then, write it directly.
112 const auto start = aos::monotonic_clock::now();
113 const ssize_t written = write(fd_, span.data(), span.size());
114 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700115 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700116 UpdateStatsForWrite(end - start, written, 1);
117 } else {
118 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuha36c8902019-12-30 18:07:15 -0800119 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700120
121 FlushAtThreshold();
Austin Schuha36c8902019-12-30 18:07:15 -0800122}
123
Brian Silverman0465fcf2020-09-24 00:29:18 -0700124void DetachedBufferWriter::Close() {
125 if (fd_ == -1) {
126 return;
127 }
128 encoder_->Finish();
129 while (encoder_->queue_size() > 0) {
130 Flush();
131 }
132 if (close(fd_) == -1) {
133 if (errno == ENOSPC) {
134 ran_out_of_space_ = true;
135 } else {
136 PLOG(ERROR) << "Closing log file failed";
137 }
138 }
139 fd_ = -1;
140 VLOG(1) << "Closed " << filename_;
141}
142
Austin Schuha36c8902019-12-30 18:07:15 -0800143void DetachedBufferWriter::Flush() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700144 const auto queue = encoder_->queue();
145 if (queue.empty()) {
Austin Schuha36c8902019-12-30 18:07:15 -0800146 return;
147 }
Brian Silverman0465fcf2020-09-24 00:29:18 -0700148 if (ran_out_of_space_) {
149 // We don't want any later data to be written after space becomes available,
150 // so refuse to write anything more once we've dropped data because we ran
151 // out of space.
152 VLOG(1) << "Ignoring queue: " << queue.size();
153 encoder_->Clear(queue.size());
154 return;
155 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700156
Austin Schuha36c8902019-12-30 18:07:15 -0800157 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700158 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
159 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800160 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700161 for (size_t i = 0; i < iovec_size; ++i) {
162 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
163 iovec_[i].iov_len = queue[i].size();
164 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800165 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700166
167 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800168 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700169 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700170 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700171
172 encoder_->Clear(iovec_size);
173
174 UpdateStatsForWrite(end - start, written, iovec_size);
175}
176
Brian Silverman0465fcf2020-09-24 00:29:18 -0700177void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
178 size_t write_size) {
179 if (write_return == -1 && errno == ENOSPC) {
180 ran_out_of_space_ = true;
181 return;
182 }
183 PCHECK(write_return >= 0) << ": write failed";
184 if (write_return < static_cast<ssize_t>(write_size)) {
185 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
186 // never seems to happen in any other case. If we ever want to log to a
187 // socket, this will happen more often. However, until we get there, we'll
188 // just assume it means we ran out of space.
189 ran_out_of_space_ = true;
190 return;
191 }
192}
193
Brian Silvermanf51499a2020-09-21 12:49:08 -0700194void DetachedBufferWriter::UpdateStatsForWrite(
195 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
196 if (duration > max_write_time_) {
197 max_write_time_ = duration;
198 max_write_time_bytes_ = written;
199 max_write_time_messages_ = iovec_size;
200 }
201 total_write_time_ += duration;
202 ++total_write_count_;
203 total_write_messages_ += iovec_size;
204 total_write_bytes_ += written;
205}
206
207void DetachedBufferWriter::FlushAtThreshold() {
208 // Flush if we are at the max number of iovs per writev, because there's no
209 // point queueing up any more data in memory. Also flush once we have enough
210 // data queued up.
211 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
212 encoder_->queue_size() >= IOV_MAX) {
213 Flush();
214 }
Austin Schuha36c8902019-12-30 18:07:15 -0800215}
216
217flatbuffers::Offset<MessageHeader> PackMessage(
218 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
219 int channel_index, LogType log_type) {
220 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
221
222 switch (log_type) {
223 case LogType::kLogMessage:
224 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800225 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700226 data_offset = fbb->CreateVector(
227 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800228 break;
229
230 case LogType::kLogDeliveryTimeOnly:
231 break;
232 }
233
234 MessageHeader::Builder message_header_builder(*fbb);
235 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800236
237 switch (log_type) {
238 case LogType::kLogRemoteMessage:
239 message_header_builder.add_queue_index(context.remote_queue_index);
240 message_header_builder.add_monotonic_sent_time(
241 context.monotonic_remote_time.time_since_epoch().count());
242 message_header_builder.add_realtime_sent_time(
243 context.realtime_remote_time.time_since_epoch().count());
244 break;
245
246 case LogType::kLogMessage:
247 case LogType::kLogMessageAndDeliveryTime:
248 case LogType::kLogDeliveryTimeOnly:
249 message_header_builder.add_queue_index(context.queue_index);
250 message_header_builder.add_monotonic_sent_time(
251 context.monotonic_event_time.time_since_epoch().count());
252 message_header_builder.add_realtime_sent_time(
253 context.realtime_event_time.time_since_epoch().count());
254 break;
255 }
Austin Schuha36c8902019-12-30 18:07:15 -0800256
257 switch (log_type) {
258 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800259 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800260 message_header_builder.add_data(data_offset);
261 break;
262
263 case LogType::kLogMessageAndDeliveryTime:
264 message_header_builder.add_data(data_offset);
265 [[fallthrough]];
266
267 case LogType::kLogDeliveryTimeOnly:
268 message_header_builder.add_monotonic_remote_time(
269 context.monotonic_remote_time.time_since_epoch().count());
270 message_header_builder.add_realtime_remote_time(
271 context.realtime_remote_time.time_since_epoch().count());
272 message_header_builder.add_remote_queue_index(context.remote_queue_index);
273 break;
274 }
275
276 return message_header_builder.Finish();
277}
278
Brian Silvermanf51499a2020-09-21 12:49:08 -0700279SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700280 static const std::string_view kXz = ".xz";
281 if (filename.substr(filename.size() - kXz.size()) == kXz) {
282#if ENABLE_LZMA
283 decoder_ = std::make_unique<LzmaDecoder>(filename);
284#else
285 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
286#endif
287 } else {
288 decoder_ = std::make_unique<DummyDecoder>(filename);
289 }
Austin Schuh05b70472020-01-01 17:11:17 -0800290}
291
292absl::Span<const uint8_t> SpanReader::ReadMessage() {
293 // Make sure we have enough for the size.
294 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
295 if (!ReadBlock()) {
296 return absl::Span<const uint8_t>();
297 }
298 }
299
300 // Now make sure we have enough for the message.
301 const size_t data_size =
302 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
303 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800304 if (data_size == sizeof(flatbuffers::uoffset_t)) {
305 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
306 LOG(ERROR) << " Rest of log file is "
307 << absl::BytesToHexString(std::string_view(
308 reinterpret_cast<const char *>(data_.data() +
309 consumed_data_),
310 data_.size() - consumed_data_));
311 return absl::Span<const uint8_t>();
312 }
Austin Schuh05b70472020-01-01 17:11:17 -0800313 while (data_.size() < consumed_data_ + data_size) {
314 if (!ReadBlock()) {
315 return absl::Span<const uint8_t>();
316 }
317 }
318
319 // And return it, consuming the data.
320 const uint8_t *data_ptr = data_.data() + consumed_data_;
321
322 consumed_data_ += data_size;
323
324 return absl::Span<const uint8_t>(data_ptr, data_size);
325}
326
Austin Schuh05b70472020-01-01 17:11:17 -0800327bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700328 // This is the amount of data we grab at a time. Doing larger chunks minimizes
329 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800330 constexpr size_t kReadSize = 256 * 1024;
331
332 // Strip off any unused data at the front.
333 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700334 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800335 consumed_data_ = 0;
336 }
337
338 const size_t starting_size = data_.size();
339
340 // This should automatically grow the backing store. It won't shrink if we
341 // get a small chunk later. This reduces allocations when we want to append
342 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700343 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800344
Brian Silvermanf51499a2020-09-21 12:49:08 -0700345 const size_t count =
346 decoder_->Read(data_.begin() + starting_size, data_.end());
347 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800348 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800349 return false;
350 }
Austin Schuh05b70472020-01-01 17:11:17 -0800351
352 return true;
353}
354
Austin Schuhadd6eb32020-11-09 21:24:26 -0800355std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800356 std::string_view filename) {
Austin Schuh6f3babe2020-01-26 20:34:50 -0800357 SpanReader span_reader(filename);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800358 absl::Span<const uint8_t> config_data = span_reader.ReadMessage();
359
360 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800361 if (config_data == absl::Span<const uint8_t>()) {
362 return std::nullopt;
363 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800364
Austin Schuh5212cad2020-09-09 23:12:09 -0700365 // And copy the config so we have it forever, removing the size prefix.
Brian Silverman354697a2020-09-22 21:06:32 -0700366 ResizeableBuffer data;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800367 data.resize(config_data.size());
368 memcpy(data.data(), config_data.begin(), data.size());
Austin Schuhe09beb12020-12-11 20:04:27 -0800369 SizePrefixedFlatbufferVector<LogFileHeader> result(std::move(data));
370 if (!result.Verify()) {
371 return std::nullopt;
372 }
373 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800374}
375
Austin Schuhadd6eb32020-11-09 21:24:26 -0800376std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800377 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700378 SpanReader span_reader(filename);
379 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
380 for (size_t i = 0; i < n + 1; ++i) {
381 data_span = span_reader.ReadMessage();
382
383 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800384 if (data_span == absl::Span<const uint8_t>()) {
385 return std::nullopt;
386 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700387 }
388
Brian Silverman354697a2020-09-22 21:06:32 -0700389 // And copy the config so we have it forever, removing the size prefix.
390 ResizeableBuffer data;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800391 data.resize(data_span.size());
392 memcpy(data.data(), data_span.begin(), data.size());
Austin Schuhe09beb12020-12-11 20:04:27 -0800393 SizePrefixedFlatbufferVector<MessageHeader> result(std::move(data));
394 if (!result.Verify()) {
395 return std::nullopt;
396 }
397 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700398}
399
Austin Schuh05b70472020-01-01 17:11:17 -0800400MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700401 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800402 raw_log_file_header_(
403 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh05b70472020-01-01 17:11:17 -0800404 // Make sure we have enough to read the size.
Austin Schuh97789fc2020-08-01 14:42:45 -0700405 absl::Span<const uint8_t> header_data = span_reader_.ReadMessage();
Austin Schuh05b70472020-01-01 17:11:17 -0800406
407 // Make sure something was read.
Austin Schuh97789fc2020-08-01 14:42:45 -0700408 CHECK(header_data != absl::Span<const uint8_t>())
409 << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800410
Austin Schuh97789fc2020-08-01 14:42:45 -0700411 // And copy the header data so we have it forever.
Brian Silverman354697a2020-09-22 21:06:32 -0700412 ResizeableBuffer header_data_copy;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800413 header_data_copy.resize(header_data.size());
414 memcpy(header_data_copy.data(), header_data.begin(), header_data_copy.size());
Austin Schuh97789fc2020-08-01 14:42:45 -0700415 raw_log_file_header_ =
Austin Schuhadd6eb32020-11-09 21:24:26 -0800416 SizePrefixedFlatbufferVector<LogFileHeader>(std::move(header_data_copy));
Austin Schuh05b70472020-01-01 17:11:17 -0800417
Austin Schuhcde938c2020-02-02 17:30:07 -0800418 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -0800419 FLAGS_max_out_of_order > 0
420 ? chrono::duration_cast<chrono::nanoseconds>(
421 chrono::duration<double>(FLAGS_max_out_of_order))
422 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800423
424 VLOG(1) << "Opened " << filename << " as node "
425 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800426}
427
Austin Schuhadd6eb32020-11-09 21:24:26 -0800428std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
429MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800430 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
431 if (msg_data == absl::Span<const uint8_t>()) {
432 return std::nullopt;
433 }
434
Brian Silverman354697a2020-09-22 21:06:32 -0700435 ResizeableBuffer result_buffer;
Austin Schuhadd6eb32020-11-09 21:24:26 -0800436 result_buffer.resize(msg_data.size());
437 memcpy(result_buffer.data(), msg_data.begin(), result_buffer.size());
438 SizePrefixedFlatbufferVector<MessageHeader> result(std::move(result_buffer));
Austin Schuh05b70472020-01-01 17:11:17 -0800439
440 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
441 chrono::nanoseconds(result.message().monotonic_sent_time()));
442
443 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800444 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800445 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800446}
447
Austin Schuhc41603c2020-10-11 16:17:37 -0700448PartsMessageReader::PartsMessageReader(LogParts log_parts)
449 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {}
450
Austin Schuhadd6eb32020-11-09 21:24:26 -0800451std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuhc41603c2020-10-11 16:17:37 -0700452PartsMessageReader::ReadMessage() {
453 while (!done_) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800454 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700455 message_reader_.ReadMessage();
456 if (message) {
457 newest_timestamp_ = message_reader_.newest_timestamp();
Austin Schuh32f68492020-11-08 21:45:51 -0800458 const monotonic_clock::time_point monotonic_sent_time(
459 chrono::nanoseconds(message->message().monotonic_sent_time()));
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800460 // TODO(austin): Does this work with startup? Might need to use the start
461 // time.
462 // TODO(austin): Does this work with startup when we don't know the remote
463 // start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800464 if (monotonic_sent_time >
465 parts_.monotonic_start_time + max_out_of_order_duration()) {
466 after_start_ = true;
467 }
468 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800469 CHECK_GE(monotonic_sent_time,
470 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800471 << ": Max out of order of " << max_out_of_order_duration().count()
472 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800473 << parts_.monotonic_start_time << " currently reading "
474 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800475 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700476 return message;
477 }
478 NextLog();
479 }
Austin Schuh32f68492020-11-08 21:45:51 -0800480 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700481 return std::nullopt;
482}
483
484void PartsMessageReader::NextLog() {
485 if (next_part_index_ == parts_.parts.size()) {
486 done_ = true;
487 return;
488 }
489 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
490 ++next_part_index_;
491}
492
Austin Schuh1be0ce42020-11-29 22:43:26 -0800493bool Message::operator<(const Message &m2) const {
494 if (this->timestamp < m2.timestamp) {
495 return true;
496 } else if (this->timestamp > m2.timestamp) {
497 return false;
498 }
499
500 if (this->channel_index < m2.channel_index) {
501 return true;
502 } else if (this->channel_index > m2.channel_index) {
503 return false;
504 }
505
506 return this->queue_index < m2.queue_index;
507}
508
509bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800510bool Message::operator==(const Message &m2) const {
511 return timestamp == m2.timestamp && channel_index == m2.channel_index &&
512 queue_index == m2.queue_index;
513}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800514
515std::ostream &operator<<(std::ostream &os, const Message &m) {
516 os << "{.channel_index=" << m.channel_index
Austin Schuhd2f96102020-12-01 20:27:29 -0800517 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
518 if (m.data.Verify()) {
519 os << ", .data="
520 << aos::FlatbufferToJson(m.data,
521 {.multi_line = false, .max_vector_size = 1});
522 }
523 os << "}";
524 return os;
525}
526
527std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
528 os << "{.channel_index=" << m.channel_index
529 << ", .queue_index=" << m.queue_index
530 << ", .monotonic_event_time=" << m.monotonic_event_time
531 << ", .realtime_event_time=" << m.realtime_event_time;
532 if (m.remote_queue_index != 0xffffffff) {
533 os << ", .remote_queue_index=" << m.remote_queue_index;
534 }
535 if (m.monotonic_remote_time != monotonic_clock::min_time) {
536 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
537 }
538 if (m.realtime_remote_time != realtime_clock::min_time) {
539 os << ", .realtime_remote_time=" << m.realtime_remote_time;
540 }
Austin Schuh8bf1e632021-01-02 22:41:04 -0800541 if (m.monotonic_timestamp_time != monotonic_clock::min_time) {
542 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
543 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800544 if (m.data.Verify()) {
545 os << ", .data="
546 << aos::FlatbufferToJson(m.data,
547 {.multi_line = false, .max_vector_size = 1});
548 }
549 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800550 return os;
551}
552
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800553LogPartsSorter::LogPartsSorter(LogParts log_parts)
554 : parts_message_reader_(log_parts) {}
555
556Message *LogPartsSorter::Front() {
557 // Queue up data until enough data has been queued that the front message is
558 // sorted enough to be safe to pop. This may do nothing, so we should make
559 // sure the nothing path is checked quickly.
560 if (sorted_until() != monotonic_clock::max_time) {
561 while (true) {
Austin Schuhb000de62020-12-03 22:00:40 -0800562 if (!messages_.empty() && messages_.begin()->timestamp < sorted_until() &&
563 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800564 break;
565 }
566
567 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> m =
568 parts_message_reader_.ReadMessage();
569 // No data left, sorted forever, work through what is left.
570 if (!m) {
571 sorted_until_ = monotonic_clock::max_time;
572 break;
573 }
574
575 messages_.insert(
576 {.channel_index = m.value().message().channel_index(),
577 .queue_index = m.value().message().queue_index(),
578 .timestamp = monotonic_clock::time_point(std::chrono::nanoseconds(
579 m.value().message().monotonic_sent_time())),
580 .data = std::move(m.value())});
581
582 // Now, update sorted_until_ to match the new message.
583 if (parts_message_reader_.newest_timestamp() >
584 monotonic_clock::min_time +
585 parts_message_reader_.max_out_of_order_duration()) {
586 sorted_until_ = parts_message_reader_.newest_timestamp() -
587 parts_message_reader_.max_out_of_order_duration();
588 } else {
589 sorted_until_ = monotonic_clock::min_time;
590 }
591 }
592 }
593
594 // Now that we have enough data queued, return a pointer to the oldest piece
595 // of data if it exists.
596 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800597 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800598 return nullptr;
599 }
600
Austin Schuh315b96b2020-12-11 21:21:12 -0800601 CHECK_GE(messages_.begin()->timestamp, last_message_time_)
602 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800603 last_message_time_ = messages_.begin()->timestamp;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800604 return &(*messages_.begin());
605}
606
607void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
608
609std::string LogPartsSorter::DebugString() const {
610 std::stringstream ss;
611 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800612 int count = 0;
613 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800614 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800615 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
616 ss << m << "\n";
617 } else if (no_dots) {
618 ss << "...\n";
619 no_dots = false;
620 }
621 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800622 }
623 ss << "] <- " << parts_message_reader_.filename();
624 return ss.str();
625}
626
Austin Schuhd2f96102020-12-01 20:27:29 -0800627NodeMerger::NodeMerger(std::vector<LogParts> parts) {
628 CHECK_GE(parts.size(), 1u);
629 const std::string part0_node = parts[0].node;
630 for (size_t i = 1; i < parts.size(); ++i) {
631 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
632 }
633 for (LogParts &part : parts) {
634 parts_sorters_.emplace_back(std::move(part));
635 }
636
Austin Schuh0ca51f32020-12-25 21:51:45 -0800637 node_ = configuration::GetNodeIndex(configuration(), part0_node);
Austin Schuhd2f96102020-12-01 20:27:29 -0800638
639 monotonic_start_time_ = monotonic_clock::max_time;
640 realtime_start_time_ = realtime_clock::max_time;
641 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
642 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
643 monotonic_start_time_ = parts_sorter.monotonic_start_time();
644 realtime_start_time_ = parts_sorter.realtime_start_time();
645 }
646 }
647}
Austin Schuh8f52ed52020-11-30 23:12:39 -0800648
Austin Schuh0ca51f32020-12-25 21:51:45 -0800649std::vector<const LogParts *> NodeMerger::Parts() const {
650 std::vector<const LogParts *> p;
651 p.reserve(parts_sorters_.size());
652 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
653 p.emplace_back(&parts_sorter.parts());
654 }
655 return p;
656}
657
Austin Schuh8f52ed52020-11-30 23:12:39 -0800658Message *NodeMerger::Front() {
659 // Return the current Front if we have one, otherwise go compute one.
660 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -0800661 Message *result = current_->Front();
662 CHECK_GE(result->timestamp, last_message_time_);
663 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800664 }
665
666 // Otherwise, do a simple search for the oldest message, deduplicating any
667 // duplicates.
668 Message *oldest = nullptr;
669 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800670 for (LogPartsSorter &parts_sorter : parts_sorters_) {
671 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800672 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800673 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800674 continue;
675 }
676 if (oldest == nullptr || *m < *oldest) {
677 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -0800678 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800679 } else if (*m == *oldest) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800680 // Found a duplicate. If there is a choice, we want the one which has the
681 // timestamp time.
682 if (!m->data.message().has_monotonic_timestamp_time()) {
683 parts_sorter.PopFront();
684 } else if (!oldest->data.message().has_monotonic_timestamp_time()) {
685 current_->PopFront();
686 current_ = &parts_sorter;
687 oldest = m;
688 } else {
689 CHECK_EQ(m->data.message().monotonic_timestamp_time(),
690 oldest->data.message().monotonic_timestamp_time());
691 parts_sorter.PopFront();
692 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800693 }
694
695 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -0800696 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800697 }
698
Austin Schuhb000de62020-12-03 22:00:40 -0800699 if (oldest) {
700 CHECK_GE(oldest->timestamp, last_message_time_);
701 last_message_time_ = oldest->timestamp;
702 } else {
703 last_message_time_ = monotonic_clock::max_time;
704 }
705
Austin Schuh8f52ed52020-11-30 23:12:39 -0800706 // Return the oldest message found. This will be nullptr if nothing was
707 // found, indicating there is nothing left.
708 return oldest;
709}
710
711void NodeMerger::PopFront() {
712 CHECK(current_ != nullptr) << "Popping before calling Front()";
713 current_->PopFront();
714 current_ = nullptr;
715}
716
Austin Schuhd2f96102020-12-01 20:27:29 -0800717TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
718 : node_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -0800719 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800720 for (const LogParts *part : node_merger_.Parts()) {
721 if (!configuration_) {
722 configuration_ = part->config;
723 } else {
724 CHECK_EQ(configuration_.get(), part->config.get());
725 }
726 }
727 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800728 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
729 // pretty simple.
730 if (configuration::MultiNode(config)) {
731 nodes_data_.resize(config->nodes()->size());
732 const Node *my_node = config->nodes()->Get(node());
733 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
734 const Node *node = config->nodes()->Get(node_index);
735 NodeData *node_data = &nodes_data_[node_index];
736 node_data->channels.resize(config->channels()->size());
737 // We should save the channel if it is delivered to the node represented
738 // by the NodeData, but not sent by that node. That combo means it is
739 // forwarded.
740 size_t channel_index = 0;
741 node_data->any_delivered = false;
742 for (const Channel *channel : *config->channels()) {
743 node_data->channels[channel_index].delivered =
744 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -0800745 configuration::ChannelIsSendableOnNode(channel, my_node) &&
746 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -0800747 node_data->any_delivered = node_data->any_delivered ||
748 node_data->channels[channel_index].delivered;
749 ++channel_index;
750 }
751 }
752
753 for (const Channel *channel : *config->channels()) {
754 source_node_.emplace_back(configuration::GetNodeIndex(
755 config, channel->source_node()->string_view()));
756 }
757 }
758}
759
760void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800761 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -0800762 CHECK_NE(timestamp_mapper->node(), node());
763 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
764
765 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
766 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
767 // we could needlessly save data.
768 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800769 VLOG(1) << "Registering on node " << node() << " for peer node "
770 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -0800771 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
772
773 timestamp_mapper->nodes_data_[node()].peer = this;
774 }
775}
776
Austin Schuh79b30942021-01-24 22:32:21 -0800777void TimestampMapper::QueueMessage(Message *m) {
778 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -0800779 .channel_index = m->channel_index,
780 .queue_index = m->queue_index,
781 .monotonic_event_time = m->timestamp,
782 .realtime_event_time = aos::realtime_clock::time_point(
783 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
784 .remote_queue_index = 0xffffffff,
785 .monotonic_remote_time = monotonic_clock::min_time,
786 .realtime_remote_time = realtime_clock::min_time,
Austin Schuh8bf1e632021-01-02 22:41:04 -0800787 .monotonic_timestamp_time = monotonic_clock::min_time,
Austin Schuh79b30942021-01-24 22:32:21 -0800788 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -0800789}
790
791TimestampedMessage *TimestampMapper::Front() {
792 // No need to fetch anything new. A previous message still exists.
793 switch (first_message_) {
794 case FirstMessage::kNeedsUpdate:
795 break;
796 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -0800797 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -0800798 case FirstMessage::kNullptr:
799 return nullptr;
800 }
801
Austin Schuh79b30942021-01-24 22:32:21 -0800802 if (matched_messages_.empty()) {
803 if (!QueueMatched()) {
804 first_message_ = FirstMessage::kNullptr;
805 return nullptr;
806 }
807 }
808 first_message_ = FirstMessage::kInMessage;
809 return &matched_messages_.front();
810}
811
812bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -0800813 if (nodes_data_.empty()) {
814 // Simple path. We are single node, so there are no timestamps to match!
815 CHECK_EQ(messages_.size(), 0u);
816 Message *m = node_merger_.Front();
817 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -0800818 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -0800819 }
Austin Schuh79b30942021-01-24 22:32:21 -0800820 // Enqueue this message into matched_messages_ so we have a place to
821 // associate remote timestamps, and return it.
822 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800823
Austin Schuh79b30942021-01-24 22:32:21 -0800824 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
825 last_message_time_ = matched_messages_.back().monotonic_event_time;
826
827 // We are thin wrapper around node_merger. Call it directly.
828 node_merger_.PopFront();
829 timestamp_callback_(&matched_messages_.back());
830 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800831 }
832
833 // We need to only add messages to the list so they get processed for messages
834 // which are delivered. Reuse the flow below which uses messages_ by just
835 // adding the new message to messages_ and continuing.
836 if (messages_.empty()) {
837 if (!Queue()) {
838 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -0800839 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -0800840 }
841
842 // Now that it has been added (and cannibalized), forget about it upstream.
843 node_merger_.PopFront();
844 }
845
846 Message *m = &(messages_.front());
847
848 if (source_node_[m->channel_index] == node()) {
849 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -0800850 QueueMessage(m);
851 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
852 last_message_time_ = matched_messages_.back().monotonic_event_time;
853 messages_.pop_front();
854 timestamp_callback_(&matched_messages_.back());
855 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800856 } else {
857 // Got a timestamp, find the matching remote data, match it, and return it.
858 Message data = MatchingMessageFor(*m);
859
860 // Return the data from the remote. The local message only has timestamp
861 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -0800862 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -0800863 .channel_index = m->channel_index,
864 .queue_index = m->queue_index,
865 .monotonic_event_time = m->timestamp,
866 .realtime_event_time = aos::realtime_clock::time_point(
867 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
868 .remote_queue_index = m->data.message().remote_queue_index(),
869 .monotonic_remote_time =
870 monotonic_clock::time_point(std::chrono::nanoseconds(
871 m->data.message().monotonic_remote_time())),
872 .realtime_remote_time = realtime_clock::time_point(
873 std::chrono::nanoseconds(m->data.message().realtime_remote_time())),
Austin Schuh8bf1e632021-01-02 22:41:04 -0800874 .monotonic_timestamp_time =
875 monotonic_clock::time_point(std::chrono::nanoseconds(
876 m->data.message().monotonic_timestamp_time())),
Austin Schuh79b30942021-01-24 22:32:21 -0800877 .data = std::move(data.data)});
878 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
879 last_message_time_ = matched_messages_.back().monotonic_event_time;
880 // Since messages_ holds the data, drop it.
881 messages_.pop_front();
882 timestamp_callback_(&matched_messages_.back());
883 return true;
884 }
885}
886
887void TimestampMapper::QueueUntil(monotonic_clock::time_point queue_time) {
888 while (last_message_time_ <= queue_time) {
889 if (!QueueMatched()) {
890 return;
891 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800892 }
893}
894
Austin Schuhe639ea12021-01-25 13:00:22 -0800895void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
896 // Make sure we have something queued first. This makes the end time
897 // calculation simpler, and is typically what folks want regardless.
898 if (matched_messages_.empty()) {
899 if (!QueueMatched()) {
900 return;
901 }
902 }
903
904 const aos::monotonic_clock::time_point end_queue_time =
905 std::max(monotonic_start_time(),
906 matched_messages_.front().monotonic_event_time) +
907 time_estimation_buffer;
908
909 // Place sorted messages on the list until we have
910 // --time_estimation_buffer_seconds seconds queued up (but queue at least
911 // until the log starts).
912 while (end_queue_time >= last_message_time_) {
913 if (!QueueMatched()) {
914 return;
915 }
916 }
917}
918
Austin Schuhd2f96102020-12-01 20:27:29 -0800919void TimestampMapper::PopFront() {
920 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
921 first_message_ = FirstMessage::kNeedsUpdate;
922
Austin Schuh79b30942021-01-24 22:32:21 -0800923 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -0800924}
925
926Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800927 // Figure out what queue index we are looking for.
928 CHECK(message.data.message().has_remote_queue_index());
929 const uint32_t remote_queue_index =
930 message.data.message().remote_queue_index();
931
932 CHECK(message.data.message().has_monotonic_remote_time());
933 CHECK(message.data.message().has_realtime_remote_time());
934
935 const monotonic_clock::time_point monotonic_remote_time(
936 std::chrono::nanoseconds(message.data.message().monotonic_remote_time()));
937 const realtime_clock::time_point realtime_remote_time(
938 std::chrono::nanoseconds(message.data.message().realtime_remote_time()));
939
Austin Schuhfecf1d82020-12-19 16:57:28 -0800940 TimestampMapper *peer = nodes_data_[source_node_[message.channel_index]].peer;
941
942 // We only register the peers which we have data for. So, if we are being
943 // asked to pull a timestamp from a peer which doesn't exist, return an empty
944 // message.
945 if (peer == nullptr) {
946 return Message{
947 .channel_index = message.channel_index,
948 .queue_index = remote_queue_index,
949 .timestamp = monotonic_remote_time,
950 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
951 }
952
953 // The queue which will have the matching data, if available.
954 std::deque<Message> *data_queue =
955 &peer->nodes_data_[node()].channels[message.channel_index].messages;
956
Austin Schuh79b30942021-01-24 22:32:21 -0800957 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -0800958
959 if (data_queue->empty()) {
960 return Message{
961 .channel_index = message.channel_index,
962 .queue_index = remote_queue_index,
963 .timestamp = monotonic_remote_time,
964 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
965 }
966
Austin Schuhd2f96102020-12-01 20:27:29 -0800967 if (remote_queue_index < data_queue->front().queue_index ||
968 remote_queue_index > data_queue->back().queue_index) {
969 return Message{
970 .channel_index = message.channel_index,
971 .queue_index = remote_queue_index,
972 .timestamp = monotonic_remote_time,
973 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
974 }
975
Austin Schuh993ccb52020-12-12 15:59:32 -0800976 // The algorithm below is constant time with some assumptions. We need there
977 // to be no missing messages in the data stream. This also assumes a queue
978 // hasn't wrapped. That is conservative, but should let us get started.
979 if (data_queue->back().queue_index - data_queue->front().queue_index + 1u ==
980 data_queue->size()) {
981 // Pull the data out and confirm that the timestamps match as expected.
982 Message result = std::move(
983 (*data_queue)[remote_queue_index - data_queue->front().queue_index]);
984
985 CHECK_EQ(result.timestamp, monotonic_remote_time)
986 << ": Queue index matches, but timestamp doesn't. Please investigate!";
987 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
988 result.data.message().realtime_sent_time())),
989 realtime_remote_time)
990 << ": Queue index matches, but timestamp doesn't. Please investigate!";
991 // Now drop the data off the front. We have deduplicated timestamps, so we
992 // are done. And all the data is in order.
993 data_queue->erase(data_queue->begin(),
994 data_queue->begin() + (1 + remote_queue_index -
995 data_queue->front().queue_index));
996 return result;
997 } else {
998 auto it = std::find_if(data_queue->begin(), data_queue->end(),
999 [remote_queue_index](const Message &m) {
1000 return m.queue_index == remote_queue_index;
1001 });
1002 if (it == data_queue->end()) {
1003 return Message{
1004 .channel_index = message.channel_index,
1005 .queue_index = remote_queue_index,
1006 .timestamp = monotonic_remote_time,
1007 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1008 }
1009
1010 Message result = std::move(*it);
1011
1012 CHECK_EQ(result.timestamp, monotonic_remote_time)
1013 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1014 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1015 result.data.message().realtime_sent_time())),
1016 realtime_remote_time)
1017 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1018
1019 data_queue->erase(it);
1020
1021 return result;
1022 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001023}
1024
Austin Schuh79b30942021-01-24 22:32:21 -08001025void TimestampMapper::QueueUnmatchedUntil(monotonic_clock::time_point t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001026 if (queued_until_ > t) {
1027 return;
1028 }
1029 while (true) {
1030 if (!messages_.empty() && messages_.back().timestamp > t) {
1031 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1032 return;
1033 }
1034
1035 if (!Queue()) {
1036 // Found nothing to add, we are out of data!
1037 queued_until_ = monotonic_clock::max_time;
1038 return;
1039 }
1040
1041 // Now that it has been added (and cannibalized), forget about it upstream.
1042 node_merger_.PopFront();
1043 }
1044}
1045
1046bool TimestampMapper::Queue() {
1047 Message *m = node_merger_.Front();
1048 if (m == nullptr) {
1049 return false;
1050 }
1051 for (NodeData &node_data : nodes_data_) {
1052 if (!node_data.any_delivered) continue;
1053 if (node_data.channels[m->channel_index].delivered) {
1054 // TODO(austin): This copies the data... Probably not worth stressing
1055 // about yet.
1056 // TODO(austin): Bound how big this can get. We tend not to send massive
1057 // data, so we can probably ignore this for a bit.
1058 node_data.channels[m->channel_index].messages.emplace_back(*m);
1059 }
1060 }
1061
1062 messages_.emplace_back(std::move(*m));
1063 return true;
1064}
1065
1066std::string TimestampMapper::DebugString() const {
1067 std::stringstream ss;
1068 ss << "node " << node() << " [\n";
1069 for (const Message &message : messages_) {
1070 ss << " " << message << "\n";
1071 }
1072 ss << "] queued_until " << queued_until_;
1073 for (const NodeData &ns : nodes_data_) {
1074 if (ns.peer == nullptr) continue;
1075 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1076 size_t channel_index = 0;
1077 for (const NodeData::ChannelData &channel_data :
1078 ns.peer->nodes_data_[node()].channels) {
1079 if (channel_data.messages.empty()) {
1080 continue;
1081 }
Austin Schuhb000de62020-12-03 22:00:40 -08001082
Austin Schuhd2f96102020-12-01 20:27:29 -08001083 ss << " channel " << channel_index << " [\n";
1084 for (const Message &m : channel_data.messages) {
1085 ss << " " << m << "\n";
1086 }
1087 ss << " ]\n";
1088 ++channel_index;
1089 }
1090 ss << "] queued_until " << ns.peer->queued_until_;
1091 }
1092 return ss.str();
1093}
1094
Austin Schuhee711052020-08-24 16:06:09 -07001095std::string MaybeNodeName(const Node *node) {
1096 if (node != nullptr) {
1097 return node->name()->str() + " ";
1098 }
1099 return "";
1100}
1101
Brian Silvermanf51499a2020-09-21 12:49:08 -07001102} // namespace aos::logger