blob: 4ca4453d98a326440c37ebacb322f1745c5cc509 [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.");
Austin Schuhbd06ae42021-03-31 22:48:21 -070033DEFINE_double(
34 flush_period, 5.0,
35 "Max time to let data sit in the queue before flushing in seconds.");
Austin Schuha36c8902019-12-30 18:07:15 -080036
Austin Schuha040c3f2021-02-13 16:09:07 -080037DEFINE_double(
38 max_out_of_order, -1,
39 "If set, this overrides the max out of order duration for a log file.");
40
Austin Schuh0e8db662021-07-06 10:43:47 -070041DEFINE_bool(workaround_double_headers, true,
42 "Some old log files have two headers at the beginning. Use the "
43 "last header as the actual header.");
44
Brian Silvermanf51499a2020-09-21 12:49:08 -070045namespace aos::logger {
Austin Schuha36c8902019-12-30 18:07:15 -080046
Austin Schuh05b70472020-01-01 17:11:17 -080047namespace chrono = std::chrono;
48
Brian Silvermanf51499a2020-09-21 12:49:08 -070049DetachedBufferWriter::DetachedBufferWriter(
50 std::string_view filename, std::unique_ptr<DetachedBufferEncoder> encoder)
51 : filename_(filename), encoder_(std::move(encoder)) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -070052 if (!util::MkdirPIfSpace(filename, 0777)) {
53 ran_out_of_space_ = true;
54 } else {
55 fd_ = open(std::string(filename).c_str(),
56 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774);
57 if (fd_ == -1 && errno == ENOSPC) {
58 ran_out_of_space_ = true;
59 } else {
60 PCHECK(fd_ != -1) << ": Failed to open " << filename << " for writing";
61 VLOG(1) << "Opened " << filename << " for writing";
62 }
63 }
Austin Schuha36c8902019-12-30 18:07:15 -080064}
65
66DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070067 Close();
68 if (ran_out_of_space_) {
69 CHECK(acknowledge_ran_out_of_space_)
70 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070071 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070072}
73
Brian Silvermand90905f2020-09-23 14:42:56 -070074DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070075 *this = std::move(other);
76}
77
Brian Silverman87ac0402020-09-17 14:47:01 -070078// When other is destroyed "soon" (which it should be because we're getting an
79// rvalue reference to it), it will flush etc all the data we have queued up
80// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -070081DetachedBufferWriter &DetachedBufferWriter::operator=(
82 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070083 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070084 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070085 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -070086 std::swap(ran_out_of_space_, other.ran_out_of_space_);
87 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070088 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070089 std::swap(max_write_time_, other.max_write_time_);
90 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
91 std::swap(max_write_time_messages_, other.max_write_time_messages_);
92 std::swap(total_write_time_, other.total_write_time_);
93 std::swap(total_write_count_, other.total_write_count_);
94 std::swap(total_write_messages_, other.total_write_messages_);
95 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070096 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -080097}
98
Brian Silvermanf51499a2020-09-21 12:49:08 -070099void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700100 if (ran_out_of_space_) {
101 // We don't want any later data to be written after space becomes
102 // available, so refuse to write anything more once we've dropped data
103 // because we ran out of space.
104 VLOG(1) << "Ignoring span: " << span.size();
105 return;
106 }
107
Austin Schuhbd06ae42021-03-31 22:48:21 -0700108 aos::monotonic_clock::time_point now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700109 if (encoder_->may_bypass() && span.size() > 4096u) {
110 // Over this threshold, we'll assume it's cheaper to add an extra
111 // syscall to write the data immediately instead of copying it to
112 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800113
Brian Silvermanf51499a2020-09-21 12:49:08 -0700114 // First, flush everything.
115 while (encoder_->queue_size() > 0u) {
116 Flush();
117 }
Austin Schuhde031b72020-01-10 19:34:41 -0800118
Brian Silvermanf51499a2020-09-21 12:49:08 -0700119 // Then, write it directly.
120 const auto start = aos::monotonic_clock::now();
121 const ssize_t written = write(fd_, span.data(), span.size());
122 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700123 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700124 UpdateStatsForWrite(end - start, written, 1);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700125 now = end;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700126 } else {
127 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuhbd06ae42021-03-31 22:48:21 -0700128 now = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800129 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700130
Austin Schuhbd06ae42021-03-31 22:48:21 -0700131 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800132}
133
Brian Silverman0465fcf2020-09-24 00:29:18 -0700134void DetachedBufferWriter::Close() {
135 if (fd_ == -1) {
136 return;
137 }
138 encoder_->Finish();
139 while (encoder_->queue_size() > 0) {
140 Flush();
141 }
142 if (close(fd_) == -1) {
143 if (errno == ENOSPC) {
144 ran_out_of_space_ = true;
145 } else {
146 PLOG(ERROR) << "Closing log file failed";
147 }
148 }
149 fd_ = -1;
150 VLOG(1) << "Closed " << filename_;
151}
152
Austin Schuha36c8902019-12-30 18:07:15 -0800153void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700154 if (ran_out_of_space_) {
155 // We don't want any later data to be written after space becomes available,
156 // so refuse to write anything more once we've dropped data because we ran
157 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700158 if (encoder_) {
159 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
160 encoder_->Clear(encoder_->queue().size());
161 } else {
162 VLOG(1) << "No queue to ignore";
163 }
164 return;
165 }
166
167 const auto queue = encoder_->queue();
168 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700169 return;
170 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700171
Austin Schuha36c8902019-12-30 18:07:15 -0800172 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700173 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
174 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800175 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700176 for (size_t i = 0; i < iovec_size; ++i) {
177 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
178 iovec_[i].iov_len = queue[i].size();
179 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800180 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700181
182 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800183 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700184 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700185 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700186
187 encoder_->Clear(iovec_size);
188
189 UpdateStatsForWrite(end - start, written, iovec_size);
190}
191
Brian Silverman0465fcf2020-09-24 00:29:18 -0700192void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
193 size_t write_size) {
194 if (write_return == -1 && errno == ENOSPC) {
195 ran_out_of_space_ = true;
196 return;
197 }
198 PCHECK(write_return >= 0) << ": write failed";
199 if (write_return < static_cast<ssize_t>(write_size)) {
200 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
201 // never seems to happen in any other case. If we ever want to log to a
202 // socket, this will happen more often. However, until we get there, we'll
203 // just assume it means we ran out of space.
204 ran_out_of_space_ = true;
205 return;
206 }
207}
208
Brian Silvermanf51499a2020-09-21 12:49:08 -0700209void DetachedBufferWriter::UpdateStatsForWrite(
210 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
211 if (duration > max_write_time_) {
212 max_write_time_ = duration;
213 max_write_time_bytes_ = written;
214 max_write_time_messages_ = iovec_size;
215 }
216 total_write_time_ += duration;
217 ++total_write_count_;
218 total_write_messages_ += iovec_size;
219 total_write_bytes_ += written;
220}
221
Austin Schuhbd06ae42021-03-31 22:48:21 -0700222void DetachedBufferWriter::FlushAtThreshold(
223 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700224 if (ran_out_of_space_) {
225 // We don't want any later data to be written after space becomes available,
226 // so refuse to write anything more once we've dropped data because we ran
227 // out of space.
228 if (encoder_) {
229 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
230 encoder_->Clear(encoder_->queue().size());
231 } else {
232 VLOG(1) << "No queue to ignore";
233 }
234 return;
235 }
236
Austin Schuhbd06ae42021-03-31 22:48:21 -0700237 // We don't want to flush the first time through. Otherwise we will flush as
238 // the log file header might be compressing, defeating any parallelism and
239 // queueing there.
240 if (last_flush_time_ == aos::monotonic_clock::min_time) {
241 last_flush_time_ = now;
242 }
243
Brian Silvermanf51499a2020-09-21 12:49:08 -0700244 // Flush if we are at the max number of iovs per writev, because there's no
245 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700246 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700247 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700248 encoder_->queue_size() >= IOV_MAX ||
249 now > last_flush_time_ +
250 chrono::duration_cast<chrono::nanoseconds>(
251 chrono::duration<double>(FLAGS_flush_period))) {
252 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700253 Flush();
254 }
Austin Schuha36c8902019-12-30 18:07:15 -0800255}
256
257flatbuffers::Offset<MessageHeader> PackMessage(
258 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
259 int channel_index, LogType log_type) {
260 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
261
262 switch (log_type) {
263 case LogType::kLogMessage:
264 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800265 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700266 data_offset = fbb->CreateVector(
267 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800268 break;
269
270 case LogType::kLogDeliveryTimeOnly:
271 break;
272 }
273
274 MessageHeader::Builder message_header_builder(*fbb);
275 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800276
277 switch (log_type) {
278 case LogType::kLogRemoteMessage:
279 message_header_builder.add_queue_index(context.remote_queue_index);
280 message_header_builder.add_monotonic_sent_time(
281 context.monotonic_remote_time.time_since_epoch().count());
282 message_header_builder.add_realtime_sent_time(
283 context.realtime_remote_time.time_since_epoch().count());
284 break;
285
286 case LogType::kLogMessage:
287 case LogType::kLogMessageAndDeliveryTime:
288 case LogType::kLogDeliveryTimeOnly:
289 message_header_builder.add_queue_index(context.queue_index);
290 message_header_builder.add_monotonic_sent_time(
291 context.monotonic_event_time.time_since_epoch().count());
292 message_header_builder.add_realtime_sent_time(
293 context.realtime_event_time.time_since_epoch().count());
294 break;
295 }
Austin Schuha36c8902019-12-30 18:07:15 -0800296
297 switch (log_type) {
298 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800299 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800300 message_header_builder.add_data(data_offset);
301 break;
302
303 case LogType::kLogMessageAndDeliveryTime:
304 message_header_builder.add_data(data_offset);
305 [[fallthrough]];
306
307 case LogType::kLogDeliveryTimeOnly:
308 message_header_builder.add_monotonic_remote_time(
309 context.monotonic_remote_time.time_since_epoch().count());
310 message_header_builder.add_realtime_remote_time(
311 context.realtime_remote_time.time_since_epoch().count());
312 message_header_builder.add_remote_queue_index(context.remote_queue_index);
313 break;
314 }
315
316 return message_header_builder.Finish();
317}
318
Brian Silvermanf51499a2020-09-21 12:49:08 -0700319SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700320 static const std::string_view kXz = ".xz";
321 if (filename.substr(filename.size() - kXz.size()) == kXz) {
322#if ENABLE_LZMA
323 decoder_ = std::make_unique<LzmaDecoder>(filename);
324#else
325 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
326#endif
327 } else {
328 decoder_ = std::make_unique<DummyDecoder>(filename);
329 }
Austin Schuh05b70472020-01-01 17:11:17 -0800330}
331
Austin Schuhcf5f6442021-07-06 10:43:28 -0700332absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800333 // Make sure we have enough for the size.
334 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
335 if (!ReadBlock()) {
336 return absl::Span<const uint8_t>();
337 }
338 }
339
340 // Now make sure we have enough for the message.
341 const size_t data_size =
342 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
343 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800344 if (data_size == sizeof(flatbuffers::uoffset_t)) {
345 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
346 LOG(ERROR) << " Rest of log file is "
347 << absl::BytesToHexString(std::string_view(
348 reinterpret_cast<const char *>(data_.data() +
349 consumed_data_),
350 data_.size() - consumed_data_));
351 return absl::Span<const uint8_t>();
352 }
Austin Schuh05b70472020-01-01 17:11:17 -0800353 while (data_.size() < consumed_data_ + data_size) {
354 if (!ReadBlock()) {
355 return absl::Span<const uint8_t>();
356 }
357 }
358
359 // And return it, consuming the data.
360 const uint8_t *data_ptr = data_.data() + consumed_data_;
361
Austin Schuh05b70472020-01-01 17:11:17 -0800362 return absl::Span<const uint8_t>(data_ptr, data_size);
363}
364
Austin Schuhcf5f6442021-07-06 10:43:28 -0700365void SpanReader::ConsumeMessage() {
366 consumed_data_ +=
367 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
368 sizeof(flatbuffers::uoffset_t);
369}
370
371absl::Span<const uint8_t> SpanReader::ReadMessage() {
372 absl::Span<const uint8_t> result = PeekMessage();
373 if (result != absl::Span<const uint8_t>()) {
374 ConsumeMessage();
375 }
376 return result;
377}
378
Austin Schuh05b70472020-01-01 17:11:17 -0800379bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700380 // This is the amount of data we grab at a time. Doing larger chunks minimizes
381 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800382 constexpr size_t kReadSize = 256 * 1024;
383
384 // Strip off any unused data at the front.
385 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700386 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800387 consumed_data_ = 0;
388 }
389
390 const size_t starting_size = data_.size();
391
392 // This should automatically grow the backing store. It won't shrink if we
393 // get a small chunk later. This reduces allocations when we want to append
394 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700395 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800396
Brian Silvermanf51499a2020-09-21 12:49:08 -0700397 const size_t count =
398 decoder_->Read(data_.begin() + starting_size, data_.end());
399 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800400 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800401 return false;
402 }
Austin Schuh05b70472020-01-01 17:11:17 -0800403
404 return true;
405}
406
Austin Schuhadd6eb32020-11-09 21:24:26 -0800407std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -0700408 SpanReader *span_reader) {
409 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800410
411 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800412 if (config_data == absl::Span<const uint8_t>()) {
413 return std::nullopt;
414 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800415
Austin Schuh5212cad2020-09-09 23:12:09 -0700416 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700417 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -0800418 if (!result.Verify()) {
419 return std::nullopt;
420 }
Austin Schuh0e8db662021-07-06 10:43:47 -0700421
422 if (FLAGS_workaround_double_headers) {
423 while (true) {
424 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
425 if (maybe_header_data == absl::Span<const uint8_t>()) {
426 break;
427 }
428
429 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
430 maybe_header_data);
431 if (maybe_header.Verify()) {
432 LOG(WARNING) << "Found duplicate LogFileHeader in "
433 << span_reader->filename();
434 ResizeableBuffer header_data_copy;
435 header_data_copy.resize(maybe_header_data.size());
436 memcpy(header_data_copy.data(), maybe_header_data.begin(),
437 header_data_copy.size());
438 result = SizePrefixedFlatbufferVector<LogFileHeader>(
439 std::move(header_data_copy));
440
441 span_reader->ConsumeMessage();
442 } else {
443 break;
444 }
445 }
446 }
Austin Schuhe09beb12020-12-11 20:04:27 -0800447 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800448}
449
Austin Schuh0e8db662021-07-06 10:43:47 -0700450std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
451 std::string_view filename) {
452 SpanReader span_reader(filename);
453 return ReadHeader(&span_reader);
454}
455
Austin Schuhadd6eb32020-11-09 21:24:26 -0800456std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800457 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700458 SpanReader span_reader(filename);
459 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
460 for (size_t i = 0; i < n + 1; ++i) {
461 data_span = span_reader.ReadMessage();
462
463 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800464 if (data_span == absl::Span<const uint8_t>()) {
465 return std::nullopt;
466 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700467 }
468
Brian Silverman354697a2020-09-22 21:06:32 -0700469 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700470 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -0800471 if (!result.Verify()) {
472 return std::nullopt;
473 }
474 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700475}
476
Austin Schuh05b70472020-01-01 17:11:17 -0800477MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700478 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800479 raw_log_file_header_(
480 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -0700481 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
482 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -0800483
484 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -0700485 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800486
Austin Schuh0e8db662021-07-06 10:43:47 -0700487 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -0800488
Austin Schuhcde938c2020-02-02 17:30:07 -0800489 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -0800490 FLAGS_max_out_of_order > 0
491 ? chrono::duration_cast<chrono::nanoseconds>(
492 chrono::duration<double>(FLAGS_max_out_of_order))
493 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800494
495 VLOG(1) << "Opened " << filename << " as node "
496 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800497}
498
Austin Schuhadd6eb32020-11-09 21:24:26 -0800499std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
500MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800501 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
502 if (msg_data == absl::Span<const uint8_t>()) {
503 return std::nullopt;
504 }
505
Austin Schuhb929c4e2021-07-12 15:32:53 -0700506 SizePrefixedFlatbufferVector<MessageHeader> result(msg_data);
Austin Schuh05b70472020-01-01 17:11:17 -0800507
Austin Schuh0e8db662021-07-06 10:43:47 -0700508 CHECK(result.Verify()) << ": Corrupted message from " << filename();
509
Austin Schuh05b70472020-01-01 17:11:17 -0800510 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
511 chrono::nanoseconds(result.message().monotonic_sent_time()));
512
513 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800514 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800515 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800516}
517
Austin Schuhc41603c2020-10-11 16:17:37 -0700518PartsMessageReader::PartsMessageReader(LogParts log_parts)
519 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {}
520
Austin Schuhadd6eb32020-11-09 21:24:26 -0800521std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuhc41603c2020-10-11 16:17:37 -0700522PartsMessageReader::ReadMessage() {
523 while (!done_) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800524 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700525 message_reader_.ReadMessage();
526 if (message) {
527 newest_timestamp_ = message_reader_.newest_timestamp();
Austin Schuh32f68492020-11-08 21:45:51 -0800528 const monotonic_clock::time_point monotonic_sent_time(
529 chrono::nanoseconds(message->message().monotonic_sent_time()));
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800530 // TODO(austin): Does this work with startup? Might need to use the start
531 // time.
532 // TODO(austin): Does this work with startup when we don't know the remote
533 // start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800534 if (monotonic_sent_time >
535 parts_.monotonic_start_time + max_out_of_order_duration()) {
536 after_start_ = true;
537 }
538 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800539 CHECK_GE(monotonic_sent_time,
540 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800541 << ": Max out of order of " << max_out_of_order_duration().count()
542 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800543 << parts_.monotonic_start_time << " currently reading "
544 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800545 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700546 return message;
547 }
548 NextLog();
549 }
Austin Schuh32f68492020-11-08 21:45:51 -0800550 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700551 return std::nullopt;
552}
553
554void PartsMessageReader::NextLog() {
555 if (next_part_index_ == parts_.parts.size()) {
556 done_ = true;
557 return;
558 }
559 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
560 ++next_part_index_;
561}
562
Austin Schuh1be0ce42020-11-29 22:43:26 -0800563bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700564 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700565
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700566 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800567 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700568 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800569 return false;
570 }
571
572 if (this->channel_index < m2.channel_index) {
573 return true;
574 } else if (this->channel_index > m2.channel_index) {
575 return false;
576 }
577
578 return this->queue_index < m2.queue_index;
579}
580
581bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800582bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700583 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700584
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700585 return timestamp.time == m2.timestamp.time &&
586 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800587}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800588
589std::ostream &operator<<(std::ostream &os, const Message &m) {
590 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700591 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Austin Schuhd2f96102020-12-01 20:27:29 -0800592 if (m.data.Verify()) {
593 os << ", .data="
594 << aos::FlatbufferToJson(m.data,
595 {.multi_line = false, .max_vector_size = 1});
596 }
597 os << "}";
598 return os;
599}
600
601std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
602 os << "{.channel_index=" << m.channel_index
603 << ", .queue_index=" << m.queue_index
604 << ", .monotonic_event_time=" << m.monotonic_event_time
605 << ", .realtime_event_time=" << m.realtime_event_time;
606 if (m.remote_queue_index != 0xffffffff) {
607 os << ", .remote_queue_index=" << m.remote_queue_index;
608 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700609 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800610 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
611 }
612 if (m.realtime_remote_time != realtime_clock::min_time) {
613 os << ", .realtime_remote_time=" << m.realtime_remote_time;
614 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700615 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800616 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
617 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800618 if (m.data.Verify()) {
619 os << ", .data="
620 << aos::FlatbufferToJson(m.data,
621 {.multi_line = false, .max_vector_size = 1});
622 }
623 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800624 return os;
625}
626
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800627LogPartsSorter::LogPartsSorter(LogParts log_parts)
628 : parts_message_reader_(log_parts) {}
629
630Message *LogPartsSorter::Front() {
631 // Queue up data until enough data has been queued that the front message is
632 // sorted enough to be safe to pop. This may do nothing, so we should make
633 // sure the nothing path is checked quickly.
634 if (sorted_until() != monotonic_clock::max_time) {
635 while (true) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700636 if (!messages_.empty() && messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -0800637 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800638 break;
639 }
640
641 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> m =
642 parts_message_reader_.ReadMessage();
643 // No data left, sorted forever, work through what is left.
644 if (!m) {
645 sorted_until_ = monotonic_clock::max_time;
646 break;
647 }
648
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700649 messages_.insert(Message{
650 .channel_index = m.value().message().channel_index(),
651 .queue_index = m.value().message().queue_index(),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700652 .timestamp =
653 BootTimestamp{
654 .boot = parts().boot_count,
655 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
656 m.value().message().monotonic_sent_time()))},
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700657 .data = std::move(m.value())});
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800658
659 // Now, update sorted_until_ to match the new message.
660 if (parts_message_reader_.newest_timestamp() >
661 monotonic_clock::min_time +
662 parts_message_reader_.max_out_of_order_duration()) {
663 sorted_until_ = parts_message_reader_.newest_timestamp() -
664 parts_message_reader_.max_out_of_order_duration();
665 } else {
666 sorted_until_ = monotonic_clock::min_time;
667 }
668 }
669 }
670
671 // Now that we have enough data queued, return a pointer to the oldest piece
672 // of data if it exists.
673 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800674 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800675 return nullptr;
676 }
677
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700678 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -0800679 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700680 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800681 return &(*messages_.begin());
682}
683
684void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
685
686std::string LogPartsSorter::DebugString() const {
687 std::stringstream ss;
688 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800689 int count = 0;
690 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800691 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800692 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
693 ss << m << "\n";
694 } else if (no_dots) {
695 ss << "...\n";
696 no_dots = false;
697 }
698 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800699 }
700 ss << "] <- " << parts_message_reader_.filename();
701 return ss.str();
702}
703
Austin Schuhd2f96102020-12-01 20:27:29 -0800704NodeMerger::NodeMerger(std::vector<LogParts> parts) {
705 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -0700706 // Enforce that we are sorting things only from a single node from a single
707 // boot.
708 const std::string_view part0_node = parts[0].node;
709 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -0800710 for (size_t i = 1; i < parts.size(); ++i) {
711 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -0700712 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
713 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -0800714 }
Austin Schuh715adc12021-06-29 22:07:39 -0700715
716 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
717
Austin Schuhd2f96102020-12-01 20:27:29 -0800718 for (LogParts &part : parts) {
719 parts_sorters_.emplace_back(std::move(part));
720 }
721
Austin Schuhd2f96102020-12-01 20:27:29 -0800722 monotonic_start_time_ = monotonic_clock::max_time;
723 realtime_start_time_ = realtime_clock::max_time;
724 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
725 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
726 monotonic_start_time_ = parts_sorter.monotonic_start_time();
727 realtime_start_time_ = parts_sorter.realtime_start_time();
728 }
729 }
730}
Austin Schuh8f52ed52020-11-30 23:12:39 -0800731
Austin Schuh0ca51f32020-12-25 21:51:45 -0800732std::vector<const LogParts *> NodeMerger::Parts() const {
733 std::vector<const LogParts *> p;
734 p.reserve(parts_sorters_.size());
735 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
736 p.emplace_back(&parts_sorter.parts());
737 }
738 return p;
739}
740
Austin Schuh8f52ed52020-11-30 23:12:39 -0800741Message *NodeMerger::Front() {
742 // Return the current Front if we have one, otherwise go compute one.
743 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -0800744 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700745 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -0800746 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800747 }
748
749 // Otherwise, do a simple search for the oldest message, deduplicating any
750 // duplicates.
751 Message *oldest = nullptr;
752 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800753 for (LogPartsSorter &parts_sorter : parts_sorters_) {
754 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800755 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800756 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800757 continue;
758 }
759 if (oldest == nullptr || *m < *oldest) {
760 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -0800761 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800762 } else if (*m == *oldest) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800763 // Found a duplicate. If there is a choice, we want the one which has the
764 // timestamp time.
765 if (!m->data.message().has_monotonic_timestamp_time()) {
766 parts_sorter.PopFront();
767 } else if (!oldest->data.message().has_monotonic_timestamp_time()) {
768 current_->PopFront();
769 current_ = &parts_sorter;
770 oldest = m;
771 } else {
772 CHECK_EQ(m->data.message().monotonic_timestamp_time(),
773 oldest->data.message().monotonic_timestamp_time());
774 parts_sorter.PopFront();
775 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800776 }
777
778 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -0800779 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800780 }
781
Austin Schuhb000de62020-12-03 22:00:40 -0800782 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700783 CHECK_GE(oldest->timestamp.time, last_message_time_);
784 last_message_time_ = oldest->timestamp.time;
Austin Schuhb000de62020-12-03 22:00:40 -0800785 } else {
786 last_message_time_ = monotonic_clock::max_time;
787 }
788
Austin Schuh8f52ed52020-11-30 23:12:39 -0800789 // Return the oldest message found. This will be nullptr if nothing was
790 // found, indicating there is nothing left.
791 return oldest;
792}
793
794void NodeMerger::PopFront() {
795 CHECK(current_ != nullptr) << "Popping before calling Front()";
796 current_->PopFront();
797 current_ = nullptr;
798}
799
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700800BootMerger::BootMerger(std::vector<LogParts> files) {
801 std::vector<std::vector<LogParts>> boots;
802
803 // Now, we need to split things out by boot.
804 for (size_t i = 0; i < files.size(); ++i) {
805 LOG(INFO) << "Trying file " << i;
806 const size_t boot_count = files[i].boot_count;
807 LOG(INFO) << "Boot count " << boot_count;
808 if (boot_count + 1 > boots.size()) {
809 boots.resize(boot_count + 1);
810 }
811 boots[boot_count].emplace_back(std::move(files[i]));
812 }
813
814 node_mergers_.reserve(boots.size());
815 for (size_t i = 0; i < boots.size(); ++i) {
816 LOG(INFO) << "Boot " << i;
817 for (auto &p : boots[i]) {
818 LOG(INFO) << "Part " << p;
819 }
820 node_mergers_.emplace_back(
821 std::make_unique<NodeMerger>(std::move(boots[i])));
822 }
823}
824
825Message *BootMerger::Front() {
826 Message *result = node_mergers_[index_]->Front();
827
828 if (result != nullptr) {
829 return result;
830 }
831
832 if (index_ + 1u == node_mergers_.size()) {
833 // At the end of the last node merger, just return.
834 return nullptr;
835 } else {
836 ++index_;
837 return Front();
838 }
839}
840
841void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
842
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700843std::vector<const LogParts *> BootMerger::Parts() const {
844 std::vector<const LogParts *> results;
845 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
846 std::vector<const LogParts *> node_parts = node_merger->Parts();
847
848 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
849 std::make_move_iterator(node_parts.end()));
850 }
851
852 return results;
853}
854
Austin Schuhd2f96102020-12-01 20:27:29 -0800855TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700856 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -0800857 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700858 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800859 if (!configuration_) {
860 configuration_ = part->config;
861 } else {
862 CHECK_EQ(configuration_.get(), part->config.get());
863 }
864 }
865 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800866 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
867 // pretty simple.
868 if (configuration::MultiNode(config)) {
869 nodes_data_.resize(config->nodes()->size());
870 const Node *my_node = config->nodes()->Get(node());
871 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
872 const Node *node = config->nodes()->Get(node_index);
873 NodeData *node_data = &nodes_data_[node_index];
874 node_data->channels.resize(config->channels()->size());
875 // We should save the channel if it is delivered to the node represented
876 // by the NodeData, but not sent by that node. That combo means it is
877 // forwarded.
878 size_t channel_index = 0;
879 node_data->any_delivered = false;
880 for (const Channel *channel : *config->channels()) {
881 node_data->channels[channel_index].delivered =
882 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -0800883 configuration::ChannelIsSendableOnNode(channel, my_node) &&
884 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -0800885 node_data->any_delivered = node_data->any_delivered ||
886 node_data->channels[channel_index].delivered;
887 ++channel_index;
888 }
889 }
890
891 for (const Channel *channel : *config->channels()) {
892 source_node_.emplace_back(configuration::GetNodeIndex(
893 config, channel->source_node()->string_view()));
894 }
895 }
896}
897
898void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800899 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -0800900 CHECK_NE(timestamp_mapper->node(), node());
901 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
902
903 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
904 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
905 // we could needlessly save data.
906 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800907 VLOG(1) << "Registering on node " << node() << " for peer node "
908 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -0800909 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
910
911 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -0700912
913 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800914 }
915}
916
Austin Schuh79b30942021-01-24 22:32:21 -0800917void TimestampMapper::QueueMessage(Message *m) {
918 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -0800919 .channel_index = m->channel_index,
920 .queue_index = m->queue_index,
921 .monotonic_event_time = m->timestamp,
922 .realtime_event_time = aos::realtime_clock::time_point(
923 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
924 .remote_queue_index = 0xffffffff,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700925 .monotonic_remote_time = BootTimestamp::min_time(),
Austin Schuhd2f96102020-12-01 20:27:29 -0800926 .realtime_remote_time = realtime_clock::min_time,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700927 .monotonic_timestamp_time = BootTimestamp::min_time(),
Austin Schuh79b30942021-01-24 22:32:21 -0800928 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -0800929}
930
931TimestampedMessage *TimestampMapper::Front() {
932 // No need to fetch anything new. A previous message still exists.
933 switch (first_message_) {
934 case FirstMessage::kNeedsUpdate:
935 break;
936 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -0800937 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -0800938 case FirstMessage::kNullptr:
939 return nullptr;
940 }
941
Austin Schuh79b30942021-01-24 22:32:21 -0800942 if (matched_messages_.empty()) {
943 if (!QueueMatched()) {
944 first_message_ = FirstMessage::kNullptr;
945 return nullptr;
946 }
947 }
948 first_message_ = FirstMessage::kInMessage;
949 return &matched_messages_.front();
950}
951
952bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -0800953 if (nodes_data_.empty()) {
954 // Simple path. We are single node, so there are no timestamps to match!
955 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700956 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -0800957 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -0800958 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -0800959 }
Austin Schuh79b30942021-01-24 22:32:21 -0800960 // Enqueue this message into matched_messages_ so we have a place to
961 // associate remote timestamps, and return it.
962 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -0800963
Austin Schuh79b30942021-01-24 22:32:21 -0800964 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
965 last_message_time_ = matched_messages_.back().monotonic_event_time;
966
967 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700968 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -0800969 timestamp_callback_(&matched_messages_.back());
970 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800971 }
972
973 // We need to only add messages to the list so they get processed for messages
974 // which are delivered. Reuse the flow below which uses messages_ by just
975 // adding the new message to messages_ and continuing.
976 if (messages_.empty()) {
977 if (!Queue()) {
978 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -0800979 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -0800980 }
981
982 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700983 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -0800984 }
985
986 Message *m = &(messages_.front());
987
988 if (source_node_[m->channel_index] == node()) {
989 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -0800990 QueueMessage(m);
991 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
992 last_message_time_ = matched_messages_.back().monotonic_event_time;
993 messages_.pop_front();
994 timestamp_callback_(&matched_messages_.back());
995 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800996 } else {
997 // Got a timestamp, find the matching remote data, match it, and return it.
998 Message data = MatchingMessageFor(*m);
999
1000 // Return the data from the remote. The local message only has timestamp
1001 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001002 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001003 .channel_index = m->channel_index,
1004 .queue_index = m->queue_index,
1005 .monotonic_event_time = m->timestamp,
1006 .realtime_event_time = aos::realtime_clock::time_point(
1007 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
1008 .remote_queue_index = m->data.message().remote_queue_index(),
1009 .monotonic_remote_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001010 // TODO(austin): 0 is wrong...
1011 {0, monotonic_clock::time_point(std::chrono::nanoseconds(
1012 m->data.message().monotonic_remote_time()))},
Austin Schuhd2f96102020-12-01 20:27:29 -08001013 .realtime_remote_time = realtime_clock::time_point(
1014 std::chrono::nanoseconds(m->data.message().realtime_remote_time())),
Austin Schuh8bf1e632021-01-02 22:41:04 -08001015 .monotonic_timestamp_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001016 {0, monotonic_clock::time_point(std::chrono::nanoseconds(
1017 m->data.message().monotonic_timestamp_time()))},
Austin Schuh79b30942021-01-24 22:32:21 -08001018 .data = std::move(data.data)});
1019 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1020 last_message_time_ = matched_messages_.back().monotonic_event_time;
1021 // Since messages_ holds the data, drop it.
1022 messages_.pop_front();
1023 timestamp_callback_(&matched_messages_.back());
1024 return true;
1025 }
1026}
1027
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001028void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001029 while (last_message_time_ <= queue_time) {
1030 if (!QueueMatched()) {
1031 return;
1032 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001033 }
1034}
1035
Austin Schuhe639ea12021-01-25 13:00:22 -08001036void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001037 // Note: queueing for time doesn't really work well across boots. So we just
1038 // assume that if you are using this, you only care about the current boot.
1039 //
1040 // TODO(austin): Is that the right concept?
1041 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001042 // Make sure we have something queued first. This makes the end time
1043 // calculation simpler, and is typically what folks want regardless.
1044 if (matched_messages_.empty()) {
1045 if (!QueueMatched()) {
1046 return;
1047 }
1048 }
1049
1050 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001051 std::max(monotonic_start_time(
1052 matched_messages_.front().monotonic_event_time.boot),
1053 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001054 time_estimation_buffer;
1055
1056 // Place sorted messages on the list until we have
1057 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1058 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001059 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001060 if (!QueueMatched()) {
1061 return;
1062 }
1063 }
1064}
1065
Austin Schuhd2f96102020-12-01 20:27:29 -08001066void TimestampMapper::PopFront() {
1067 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
1068 first_message_ = FirstMessage::kNeedsUpdate;
1069
Austin Schuh79b30942021-01-24 22:32:21 -08001070 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001071}
1072
1073Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001074 // Figure out what queue index we are looking for.
1075 CHECK(message.data.message().has_remote_queue_index());
1076 const uint32_t remote_queue_index =
1077 message.data.message().remote_queue_index();
1078
1079 CHECK(message.data.message().has_monotonic_remote_time());
1080 CHECK(message.data.message().has_realtime_remote_time());
1081
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001082 const BootTimestamp monotonic_remote_time{
1083 .boot = 0,
1084 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
1085 message.data.message().monotonic_remote_time()))};
Austin Schuhd2f96102020-12-01 20:27:29 -08001086 const realtime_clock::time_point realtime_remote_time(
1087 std::chrono::nanoseconds(message.data.message().realtime_remote_time()));
1088
Austin Schuhfecf1d82020-12-19 16:57:28 -08001089 TimestampMapper *peer = nodes_data_[source_node_[message.channel_index]].peer;
1090
1091 // We only register the peers which we have data for. So, if we are being
1092 // asked to pull a timestamp from a peer which doesn't exist, return an empty
1093 // message.
1094 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001095 // TODO(austin): Make sure the tests hit all these paths with a boot count
1096 // of 1...
Austin Schuhfecf1d82020-12-19 16:57:28 -08001097 return Message{
1098 .channel_index = message.channel_index,
1099 .queue_index = remote_queue_index,
1100 .timestamp = monotonic_remote_time,
1101 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1102 }
1103
1104 // The queue which will have the matching data, if available.
1105 std::deque<Message> *data_queue =
1106 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1107
Austin Schuh79b30942021-01-24 22:32:21 -08001108 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001109
1110 if (data_queue->empty()) {
1111 return Message{
1112 .channel_index = message.channel_index,
1113 .queue_index = remote_queue_index,
1114 .timestamp = monotonic_remote_time,
1115 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1116 }
1117
Austin Schuhd2f96102020-12-01 20:27:29 -08001118 if (remote_queue_index < data_queue->front().queue_index ||
1119 remote_queue_index > data_queue->back().queue_index) {
1120 return Message{
1121 .channel_index = message.channel_index,
1122 .queue_index = remote_queue_index,
1123 .timestamp = monotonic_remote_time,
1124 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1125 }
1126
Austin Schuh993ccb52020-12-12 15:59:32 -08001127 // The algorithm below is constant time with some assumptions. We need there
1128 // to be no missing messages in the data stream. This also assumes a queue
1129 // hasn't wrapped. That is conservative, but should let us get started.
1130 if (data_queue->back().queue_index - data_queue->front().queue_index + 1u ==
1131 data_queue->size()) {
1132 // Pull the data out and confirm that the timestamps match as expected.
1133 Message result = std::move(
1134 (*data_queue)[remote_queue_index - data_queue->front().queue_index]);
1135
1136 CHECK_EQ(result.timestamp, monotonic_remote_time)
1137 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1138 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1139 result.data.message().realtime_sent_time())),
1140 realtime_remote_time)
1141 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1142 // Now drop the data off the front. We have deduplicated timestamps, so we
1143 // are done. And all the data is in order.
1144 data_queue->erase(data_queue->begin(),
1145 data_queue->begin() + (1 + remote_queue_index -
1146 data_queue->front().queue_index));
1147 return result;
1148 } else {
1149 auto it = std::find_if(data_queue->begin(), data_queue->end(),
1150 [remote_queue_index](const Message &m) {
1151 return m.queue_index == remote_queue_index;
1152 });
1153 if (it == data_queue->end()) {
1154 return Message{
1155 .channel_index = message.channel_index,
1156 .queue_index = remote_queue_index,
1157 .timestamp = monotonic_remote_time,
1158 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1159 }
1160
1161 Message result = std::move(*it);
1162
1163 CHECK_EQ(result.timestamp, monotonic_remote_time)
1164 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1165 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1166 result.data.message().realtime_sent_time())),
1167 realtime_remote_time)
1168 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1169
1170 data_queue->erase(it);
1171
1172 return result;
1173 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001174}
1175
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001176void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001177 if (queued_until_ > t) {
1178 return;
1179 }
1180 while (true) {
1181 if (!messages_.empty() && messages_.back().timestamp > t) {
1182 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1183 return;
1184 }
1185
1186 if (!Queue()) {
1187 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001188 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001189 return;
1190 }
1191
1192 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001193 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001194 }
1195}
1196
1197bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001198 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001199 if (m == nullptr) {
1200 return false;
1201 }
1202 for (NodeData &node_data : nodes_data_) {
1203 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07001204 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08001205 if (node_data.channels[m->channel_index].delivered) {
1206 // TODO(austin): This copies the data... Probably not worth stressing
1207 // about yet.
1208 // TODO(austin): Bound how big this can get. We tend not to send massive
1209 // data, so we can probably ignore this for a bit.
1210 node_data.channels[m->channel_index].messages.emplace_back(*m);
1211 }
1212 }
1213
1214 messages_.emplace_back(std::move(*m));
1215 return true;
1216}
1217
1218std::string TimestampMapper::DebugString() const {
1219 std::stringstream ss;
1220 ss << "node " << node() << " [\n";
1221 for (const Message &message : messages_) {
1222 ss << " " << message << "\n";
1223 }
1224 ss << "] queued_until " << queued_until_;
1225 for (const NodeData &ns : nodes_data_) {
1226 if (ns.peer == nullptr) continue;
1227 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1228 size_t channel_index = 0;
1229 for (const NodeData::ChannelData &channel_data :
1230 ns.peer->nodes_data_[node()].channels) {
1231 if (channel_data.messages.empty()) {
1232 continue;
1233 }
Austin Schuhb000de62020-12-03 22:00:40 -08001234
Austin Schuhd2f96102020-12-01 20:27:29 -08001235 ss << " channel " << channel_index << " [\n";
1236 for (const Message &m : channel_data.messages) {
1237 ss << " " << m << "\n";
1238 }
1239 ss << " ]\n";
1240 ++channel_index;
1241 }
1242 ss << "] queued_until " << ns.peer->queued_until_;
1243 }
1244 return ss.str();
1245}
1246
Austin Schuhee711052020-08-24 16:06:09 -07001247std::string MaybeNodeName(const Node *node) {
1248 if (node != nullptr) {
1249 return node->name()->str() + " ";
1250 }
1251 return "";
1252}
1253
Brian Silvermanf51499a2020-09-21 12:49:08 -07001254} // namespace aos::logger