blob: 89be8285590899793ef572e5cc6bf3cd2c2839d9 [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)
Austin Schuh48507722021-07-17 17:29:24 -0700519 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
520 ComputeBootCounts();
521}
522
523void PartsMessageReader::ComputeBootCounts() {
524 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
525 std::nullopt);
526
527 // We have 3 vintages of log files with different amounts of information.
528 if (log_file_header()->has_boot_uuids()) {
529 // The new hotness with the boots explicitly listed out. We can use the log
530 // file header to compute the boot count of all relevant nodes.
531 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
532 size_t node_index = 0;
533 for (const flatbuffers::String *boot_uuid :
534 *log_file_header()->boot_uuids()) {
535 CHECK(parts_.boots);
536 if (boot_uuid->size() != 0) {
537 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
538 if (it != parts_.boots->boot_count_map.end()) {
539 boot_counts_[node_index] = it->second;
540 }
541 } else if (parts().boots->boots[node_index].size() == 1u) {
542 boot_counts_[node_index] = 0;
543 }
544 ++node_index;
545 }
546 } else {
547 // Older multi-node logs which are guarenteed to have UUIDs logged, or
548 // single node log files with boot UUIDs in the header. We only know how to
549 // order certain boots in certain circumstances.
550 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
551 for (size_t node_index = 0; node_index < boot_counts_.size();
552 ++node_index) {
553 CHECK(parts_.boots);
554 if (parts().boots->boots[node_index].size() == 1u) {
555 boot_counts_[node_index] = 0;
556 }
557 }
558 } else {
559 // Really old single node logs without any UUIDs. They can't reboot.
560 CHECK_EQ(boot_counts_.size(), 1u);
561 boot_counts_[0] = 0u;
562 }
563 }
564}
Austin Schuhc41603c2020-10-11 16:17:37 -0700565
Austin Schuhadd6eb32020-11-09 21:24:26 -0800566std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuhc41603c2020-10-11 16:17:37 -0700567PartsMessageReader::ReadMessage() {
568 while (!done_) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800569 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700570 message_reader_.ReadMessage();
571 if (message) {
572 newest_timestamp_ = message_reader_.newest_timestamp();
Austin Schuh32f68492020-11-08 21:45:51 -0800573 const monotonic_clock::time_point monotonic_sent_time(
574 chrono::nanoseconds(message->message().monotonic_sent_time()));
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800575 // TODO(austin): Does this work with startup? Might need to use the start
576 // time.
577 // TODO(austin): Does this work with startup when we don't know the remote
578 // start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800579 if (monotonic_sent_time >
580 parts_.monotonic_start_time + max_out_of_order_duration()) {
581 after_start_ = true;
582 }
583 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800584 CHECK_GE(monotonic_sent_time,
585 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800586 << ": Max out of order of " << max_out_of_order_duration().count()
587 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800588 << parts_.monotonic_start_time << " currently reading "
589 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800590 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700591 return message;
592 }
593 NextLog();
594 }
Austin Schuh32f68492020-11-08 21:45:51 -0800595 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700596 return std::nullopt;
597}
598
599void PartsMessageReader::NextLog() {
600 if (next_part_index_ == parts_.parts.size()) {
601 done_ = true;
602 return;
603 }
604 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
Austin Schuh48507722021-07-17 17:29:24 -0700605 ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700606 ++next_part_index_;
607}
608
Austin Schuh1be0ce42020-11-29 22:43:26 -0800609bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700610 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700611
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700612 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800613 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700614 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800615 return false;
616 }
617
618 if (this->channel_index < m2.channel_index) {
619 return true;
620 } else if (this->channel_index > m2.channel_index) {
621 return false;
622 }
623
624 return this->queue_index < m2.queue_index;
625}
626
627bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800628bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700629 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700630
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700631 return timestamp.time == m2.timestamp.time &&
632 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800633}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800634
635std::ostream &operator<<(std::ostream &os, const Message &m) {
636 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700637 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Austin Schuhd2f96102020-12-01 20:27:29 -0800638 if (m.data.Verify()) {
639 os << ", .data="
640 << aos::FlatbufferToJson(m.data,
641 {.multi_line = false, .max_vector_size = 1});
642 }
643 os << "}";
644 return os;
645}
646
647std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
648 os << "{.channel_index=" << m.channel_index
649 << ", .queue_index=" << m.queue_index
650 << ", .monotonic_event_time=" << m.monotonic_event_time
651 << ", .realtime_event_time=" << m.realtime_event_time;
652 if (m.remote_queue_index != 0xffffffff) {
653 os << ", .remote_queue_index=" << m.remote_queue_index;
654 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700655 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800656 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
657 }
658 if (m.realtime_remote_time != realtime_clock::min_time) {
659 os << ", .realtime_remote_time=" << m.realtime_remote_time;
660 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700661 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800662 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
663 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800664 if (m.data.Verify()) {
665 os << ", .data="
666 << aos::FlatbufferToJson(m.data,
667 {.multi_line = false, .max_vector_size = 1});
668 }
669 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800670 return os;
671}
672
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800673LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700674 : parts_message_reader_(log_parts),
675 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
676}
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800677
678Message *LogPartsSorter::Front() {
679 // Queue up data until enough data has been queued that the front message is
680 // sorted enough to be safe to pop. This may do nothing, so we should make
681 // sure the nothing path is checked quickly.
682 if (sorted_until() != monotonic_clock::max_time) {
683 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -0700684 if (!messages_.empty() &&
685 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -0800686 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800687 break;
688 }
689
690 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> m =
691 parts_message_reader_.ReadMessage();
692 // No data left, sorted forever, work through what is left.
693 if (!m) {
694 sorted_until_ = monotonic_clock::max_time;
695 break;
696 }
697
Austin Schuh48507722021-07-17 17:29:24 -0700698 size_t monotonic_timestamp_boot = 0;
699 if (m.value().message().has_monotonic_timestamp_time()) {
700 monotonic_timestamp_boot = parts().logger_boot_count;
701 }
702 size_t monotonic_remote_boot = 0xffffff;
703
704 if (m.value().message().has_monotonic_remote_time()) {
705 std::optional<size_t> boot = parts_message_reader_.boot_count(
706 source_node_index_[m->message().channel_index()]);
707 CHECK(boot) << ": Failed to find boot for node "
708 << source_node_index_[m->message().channel_index()];
709 monotonic_remote_boot = *boot;
710 }
711
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700712 messages_.insert(Message{
713 .channel_index = m.value().message().channel_index(),
714 .queue_index = m.value().message().queue_index(),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700715 .timestamp =
716 BootTimestamp{
717 .boot = parts().boot_count,
718 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
719 m.value().message().monotonic_sent_time()))},
Austin Schuh48507722021-07-17 17:29:24 -0700720 .monotonic_remote_boot = monotonic_remote_boot,
721 .monotonic_timestamp_boot = monotonic_timestamp_boot,
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700722 .data = std::move(m.value())});
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800723
724 // Now, update sorted_until_ to match the new message.
725 if (parts_message_reader_.newest_timestamp() >
726 monotonic_clock::min_time +
727 parts_message_reader_.max_out_of_order_duration()) {
728 sorted_until_ = parts_message_reader_.newest_timestamp() -
729 parts_message_reader_.max_out_of_order_duration();
730 } else {
731 sorted_until_ = monotonic_clock::min_time;
732 }
733 }
734 }
735
736 // Now that we have enough data queued, return a pointer to the oldest piece
737 // of data if it exists.
738 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800739 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800740 return nullptr;
741 }
742
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700743 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -0800744 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700745 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800746 return &(*messages_.begin());
747}
748
749void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
750
751std::string LogPartsSorter::DebugString() const {
752 std::stringstream ss;
753 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800754 int count = 0;
755 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800756 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800757 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
758 ss << m << "\n";
759 } else if (no_dots) {
760 ss << "...\n";
761 no_dots = false;
762 }
763 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800764 }
765 ss << "] <- " << parts_message_reader_.filename();
766 return ss.str();
767}
768
Austin Schuhd2f96102020-12-01 20:27:29 -0800769NodeMerger::NodeMerger(std::vector<LogParts> parts) {
770 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -0700771 // Enforce that we are sorting things only from a single node from a single
772 // boot.
773 const std::string_view part0_node = parts[0].node;
774 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -0800775 for (size_t i = 1; i < parts.size(); ++i) {
776 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -0700777 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
778 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -0800779 }
Austin Schuh715adc12021-06-29 22:07:39 -0700780
781 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
782
Austin Schuhd2f96102020-12-01 20:27:29 -0800783 for (LogParts &part : parts) {
784 parts_sorters_.emplace_back(std::move(part));
785 }
786
Austin Schuhd2f96102020-12-01 20:27:29 -0800787 monotonic_start_time_ = monotonic_clock::max_time;
788 realtime_start_time_ = realtime_clock::max_time;
789 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
790 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
791 monotonic_start_time_ = parts_sorter.monotonic_start_time();
792 realtime_start_time_ = parts_sorter.realtime_start_time();
793 }
794 }
795}
Austin Schuh8f52ed52020-11-30 23:12:39 -0800796
Austin Schuh0ca51f32020-12-25 21:51:45 -0800797std::vector<const LogParts *> NodeMerger::Parts() const {
798 std::vector<const LogParts *> p;
799 p.reserve(parts_sorters_.size());
800 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
801 p.emplace_back(&parts_sorter.parts());
802 }
803 return p;
804}
805
Austin Schuh8f52ed52020-11-30 23:12:39 -0800806Message *NodeMerger::Front() {
807 // Return the current Front if we have one, otherwise go compute one.
808 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -0800809 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700810 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -0800811 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800812 }
813
814 // Otherwise, do a simple search for the oldest message, deduplicating any
815 // duplicates.
816 Message *oldest = nullptr;
817 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800818 for (LogPartsSorter &parts_sorter : parts_sorters_) {
819 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800820 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800821 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800822 continue;
823 }
824 if (oldest == nullptr || *m < *oldest) {
825 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -0800826 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800827 } else if (*m == *oldest) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800828 // Found a duplicate. If there is a choice, we want the one which has the
829 // timestamp time.
830 if (!m->data.message().has_monotonic_timestamp_time()) {
831 parts_sorter.PopFront();
832 } else if (!oldest->data.message().has_monotonic_timestamp_time()) {
833 current_->PopFront();
834 current_ = &parts_sorter;
835 oldest = m;
836 } else {
837 CHECK_EQ(m->data.message().monotonic_timestamp_time(),
838 oldest->data.message().monotonic_timestamp_time());
839 parts_sorter.PopFront();
840 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800841 }
842
843 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -0800844 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800845 }
846
Austin Schuhb000de62020-12-03 22:00:40 -0800847 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700848 CHECK_GE(oldest->timestamp.time, last_message_time_);
849 last_message_time_ = oldest->timestamp.time;
Austin Schuhb000de62020-12-03 22:00:40 -0800850 } else {
851 last_message_time_ = monotonic_clock::max_time;
852 }
853
Austin Schuh8f52ed52020-11-30 23:12:39 -0800854 // Return the oldest message found. This will be nullptr if nothing was
855 // found, indicating there is nothing left.
856 return oldest;
857}
858
859void NodeMerger::PopFront() {
860 CHECK(current_ != nullptr) << "Popping before calling Front()";
861 current_->PopFront();
862 current_ = nullptr;
863}
864
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700865BootMerger::BootMerger(std::vector<LogParts> files) {
866 std::vector<std::vector<LogParts>> boots;
867
868 // Now, we need to split things out by boot.
869 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700870 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700871 if (boot_count + 1 > boots.size()) {
872 boots.resize(boot_count + 1);
873 }
874 boots[boot_count].emplace_back(std::move(files[i]));
875 }
876
877 node_mergers_.reserve(boots.size());
878 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -0700879 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700880 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -0700881 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700882 }
883 node_mergers_.emplace_back(
884 std::make_unique<NodeMerger>(std::move(boots[i])));
885 }
886}
887
888Message *BootMerger::Front() {
889 Message *result = node_mergers_[index_]->Front();
890
891 if (result != nullptr) {
892 return result;
893 }
894
895 if (index_ + 1u == node_mergers_.size()) {
896 // At the end of the last node merger, just return.
897 return nullptr;
898 } else {
899 ++index_;
900 return Front();
901 }
902}
903
904void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
905
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700906std::vector<const LogParts *> BootMerger::Parts() const {
907 std::vector<const LogParts *> results;
908 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
909 std::vector<const LogParts *> node_parts = node_merger->Parts();
910
911 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
912 std::make_move_iterator(node_parts.end()));
913 }
914
915 return results;
916}
917
Austin Schuhd2f96102020-12-01 20:27:29 -0800918TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700919 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -0800920 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700921 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800922 if (!configuration_) {
923 configuration_ = part->config;
924 } else {
925 CHECK_EQ(configuration_.get(), part->config.get());
926 }
927 }
928 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800929 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
930 // pretty simple.
931 if (configuration::MultiNode(config)) {
932 nodes_data_.resize(config->nodes()->size());
933 const Node *my_node = config->nodes()->Get(node());
934 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
935 const Node *node = config->nodes()->Get(node_index);
936 NodeData *node_data = &nodes_data_[node_index];
937 node_data->channels.resize(config->channels()->size());
938 // We should save the channel if it is delivered to the node represented
939 // by the NodeData, but not sent by that node. That combo means it is
940 // forwarded.
941 size_t channel_index = 0;
942 node_data->any_delivered = false;
943 for (const Channel *channel : *config->channels()) {
944 node_data->channels[channel_index].delivered =
945 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -0800946 configuration::ChannelIsSendableOnNode(channel, my_node) &&
947 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -0800948 node_data->any_delivered = node_data->any_delivered ||
949 node_data->channels[channel_index].delivered;
950 ++channel_index;
951 }
952 }
953
954 for (const Channel *channel : *config->channels()) {
955 source_node_.emplace_back(configuration::GetNodeIndex(
956 config, channel->source_node()->string_view()));
957 }
958 }
959}
960
961void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800962 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -0800963 CHECK_NE(timestamp_mapper->node(), node());
964 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
965
966 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
967 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
968 // we could needlessly save data.
969 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800970 VLOG(1) << "Registering on node " << node() << " for peer node "
971 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -0800972 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
973
974 timestamp_mapper->nodes_data_[node()].peer = this;
975 }
976}
977
Austin Schuh79b30942021-01-24 22:32:21 -0800978void TimestampMapper::QueueMessage(Message *m) {
979 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -0800980 .channel_index = m->channel_index,
981 .queue_index = m->queue_index,
982 .monotonic_event_time = m->timestamp,
983 .realtime_event_time = aos::realtime_clock::time_point(
984 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
985 .remote_queue_index = 0xffffffff,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700986 .monotonic_remote_time = BootTimestamp::min_time(),
Austin Schuhd2f96102020-12-01 20:27:29 -0800987 .realtime_remote_time = realtime_clock::min_time,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700988 .monotonic_timestamp_time = BootTimestamp::min_time(),
Austin Schuh79b30942021-01-24 22:32:21 -0800989 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -0800990}
991
992TimestampedMessage *TimestampMapper::Front() {
993 // No need to fetch anything new. A previous message still exists.
994 switch (first_message_) {
995 case FirstMessage::kNeedsUpdate:
996 break;
997 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -0800998 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -0800999 case FirstMessage::kNullptr:
1000 return nullptr;
1001 }
1002
Austin Schuh79b30942021-01-24 22:32:21 -08001003 if (matched_messages_.empty()) {
1004 if (!QueueMatched()) {
1005 first_message_ = FirstMessage::kNullptr;
1006 return nullptr;
1007 }
1008 }
1009 first_message_ = FirstMessage::kInMessage;
1010 return &matched_messages_.front();
1011}
1012
1013bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08001014 if (nodes_data_.empty()) {
1015 // Simple path. We are single node, so there are no timestamps to match!
1016 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001017 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001018 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -08001019 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001020 }
Austin Schuh79b30942021-01-24 22:32:21 -08001021 // Enqueue this message into matched_messages_ so we have a place to
1022 // associate remote timestamps, and return it.
1023 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08001024
Austin Schuh79b30942021-01-24 22:32:21 -08001025 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1026 last_message_time_ = matched_messages_.back().monotonic_event_time;
1027
1028 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001029 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08001030 timestamp_callback_(&matched_messages_.back());
1031 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001032 }
1033
1034 // We need to only add messages to the list so they get processed for messages
1035 // which are delivered. Reuse the flow below which uses messages_ by just
1036 // adding the new message to messages_ and continuing.
1037 if (messages_.empty()) {
1038 if (!Queue()) {
1039 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -08001040 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001041 }
1042
1043 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001044 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001045 }
1046
1047 Message *m = &(messages_.front());
1048
1049 if (source_node_[m->channel_index] == node()) {
1050 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08001051 QueueMessage(m);
1052 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1053 last_message_time_ = matched_messages_.back().monotonic_event_time;
1054 messages_.pop_front();
1055 timestamp_callback_(&matched_messages_.back());
1056 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001057 } else {
1058 // Got a timestamp, find the matching remote data, match it, and return it.
1059 Message data = MatchingMessageFor(*m);
1060
1061 // Return the data from the remote. The local message only has timestamp
1062 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001063 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001064 .channel_index = m->channel_index,
1065 .queue_index = m->queue_index,
1066 .monotonic_event_time = m->timestamp,
1067 .realtime_event_time = aos::realtime_clock::time_point(
1068 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
1069 .remote_queue_index = m->data.message().remote_queue_index(),
1070 .monotonic_remote_time =
Austin Schuh48507722021-07-17 17:29:24 -07001071 {m->monotonic_remote_boot,
1072 monotonic_clock::time_point(std::chrono::nanoseconds(
1073 m->data.message().monotonic_remote_time()))},
Austin Schuhd2f96102020-12-01 20:27:29 -08001074 .realtime_remote_time = realtime_clock::time_point(
1075 std::chrono::nanoseconds(m->data.message().realtime_remote_time())),
Austin Schuh8bf1e632021-01-02 22:41:04 -08001076 .monotonic_timestamp_time =
Austin Schuh48507722021-07-17 17:29:24 -07001077 {m->monotonic_timestamp_boot,
1078 monotonic_clock::time_point(std::chrono::nanoseconds(
1079 m->data.message().monotonic_timestamp_time()))},
Austin Schuh79b30942021-01-24 22:32:21 -08001080 .data = std::move(data.data)});
1081 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1082 last_message_time_ = matched_messages_.back().monotonic_event_time;
1083 // Since messages_ holds the data, drop it.
1084 messages_.pop_front();
1085 timestamp_callback_(&matched_messages_.back());
1086 return true;
1087 }
1088}
1089
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001090void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001091 while (last_message_time_ <= queue_time) {
1092 if (!QueueMatched()) {
1093 return;
1094 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001095 }
1096}
1097
Austin Schuhe639ea12021-01-25 13:00:22 -08001098void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001099 // Note: queueing for time doesn't really work well across boots. So we just
1100 // assume that if you are using this, you only care about the current boot.
1101 //
1102 // TODO(austin): Is that the right concept?
1103 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001104 // Make sure we have something queued first. This makes the end time
1105 // calculation simpler, and is typically what folks want regardless.
1106 if (matched_messages_.empty()) {
1107 if (!QueueMatched()) {
1108 return;
1109 }
1110 }
1111
1112 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001113 std::max(monotonic_start_time(
1114 matched_messages_.front().monotonic_event_time.boot),
1115 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001116 time_estimation_buffer;
1117
1118 // Place sorted messages on the list until we have
1119 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1120 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001121 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001122 if (!QueueMatched()) {
1123 return;
1124 }
1125 }
1126}
1127
Austin Schuhd2f96102020-12-01 20:27:29 -08001128void TimestampMapper::PopFront() {
1129 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
1130 first_message_ = FirstMessage::kNeedsUpdate;
1131
Austin Schuh79b30942021-01-24 22:32:21 -08001132 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001133}
1134
1135Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001136 // Figure out what queue index we are looking for.
1137 CHECK(message.data.message().has_remote_queue_index());
1138 const uint32_t remote_queue_index =
1139 message.data.message().remote_queue_index();
1140
1141 CHECK(message.data.message().has_monotonic_remote_time());
1142 CHECK(message.data.message().has_realtime_remote_time());
1143
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001144 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07001145 .boot = message.monotonic_remote_boot,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001146 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
1147 message.data.message().monotonic_remote_time()))};
Austin Schuhd2f96102020-12-01 20:27:29 -08001148 const realtime_clock::time_point realtime_remote_time(
1149 std::chrono::nanoseconds(message.data.message().realtime_remote_time()));
1150
Austin Schuhfecf1d82020-12-19 16:57:28 -08001151 TimestampMapper *peer = nodes_data_[source_node_[message.channel_index]].peer;
1152
1153 // We only register the peers which we have data for. So, if we are being
1154 // asked to pull a timestamp from a peer which doesn't exist, return an empty
1155 // message.
1156 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001157 // TODO(austin): Make sure the tests hit all these paths with a boot count
1158 // of 1...
Austin Schuhfecf1d82020-12-19 16:57:28 -08001159 return Message{
1160 .channel_index = message.channel_index,
1161 .queue_index = remote_queue_index,
1162 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001163 .monotonic_remote_boot = 0xffffff,
1164 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhfecf1d82020-12-19 16:57:28 -08001165 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1166 }
1167
1168 // The queue which will have the matching data, if available.
1169 std::deque<Message> *data_queue =
1170 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1171
Austin Schuh79b30942021-01-24 22:32:21 -08001172 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001173
1174 if (data_queue->empty()) {
1175 return Message{
1176 .channel_index = message.channel_index,
1177 .queue_index = remote_queue_index,
1178 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001179 .monotonic_remote_boot = 0xffffff,
1180 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhd2f96102020-12-01 20:27:29 -08001181 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1182 }
1183
Austin Schuhd2f96102020-12-01 20:27:29 -08001184 if (remote_queue_index < data_queue->front().queue_index ||
1185 remote_queue_index > data_queue->back().queue_index) {
1186 return Message{
1187 .channel_index = message.channel_index,
1188 .queue_index = remote_queue_index,
1189 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001190 .monotonic_remote_boot = 0xffffff,
1191 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhd2f96102020-12-01 20:27:29 -08001192 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1193 }
1194
Austin Schuh993ccb52020-12-12 15:59:32 -08001195 // The algorithm below is constant time with some assumptions. We need there
1196 // to be no missing messages in the data stream. This also assumes a queue
1197 // hasn't wrapped. That is conservative, but should let us get started.
1198 if (data_queue->back().queue_index - data_queue->front().queue_index + 1u ==
1199 data_queue->size()) {
1200 // Pull the data out and confirm that the timestamps match as expected.
1201 Message result = std::move(
1202 (*data_queue)[remote_queue_index - data_queue->front().queue_index]);
1203
1204 CHECK_EQ(result.timestamp, monotonic_remote_time)
1205 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1206 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1207 result.data.message().realtime_sent_time())),
1208 realtime_remote_time)
1209 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1210 // Now drop the data off the front. We have deduplicated timestamps, so we
1211 // are done. And all the data is in order.
1212 data_queue->erase(data_queue->begin(),
1213 data_queue->begin() + (1 + remote_queue_index -
1214 data_queue->front().queue_index));
1215 return result;
1216 } else {
1217 auto it = std::find_if(data_queue->begin(), data_queue->end(),
1218 [remote_queue_index](const Message &m) {
1219 return m.queue_index == remote_queue_index;
1220 });
1221 if (it == data_queue->end()) {
1222 return Message{
1223 .channel_index = message.channel_index,
1224 .queue_index = remote_queue_index,
1225 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001226 .monotonic_remote_boot = 0xffffff,
1227 .monotonic_timestamp_boot = 0xffffff,
Austin Schuh993ccb52020-12-12 15:59:32 -08001228 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1229 }
1230
1231 Message result = std::move(*it);
1232
1233 CHECK_EQ(result.timestamp, monotonic_remote_time)
1234 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1235 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1236 result.data.message().realtime_sent_time())),
1237 realtime_remote_time)
1238 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1239
1240 data_queue->erase(it);
1241
1242 return result;
1243 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001244}
1245
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001246void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001247 if (queued_until_ > t) {
1248 return;
1249 }
1250 while (true) {
1251 if (!messages_.empty() && messages_.back().timestamp > t) {
1252 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1253 return;
1254 }
1255
1256 if (!Queue()) {
1257 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001258 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001259 return;
1260 }
1261
1262 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001263 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001264 }
1265}
1266
1267bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001268 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001269 if (m == nullptr) {
1270 return false;
1271 }
1272 for (NodeData &node_data : nodes_data_) {
1273 if (!node_data.any_delivered) continue;
1274 if (node_data.channels[m->channel_index].delivered) {
1275 // TODO(austin): This copies the data... Probably not worth stressing
1276 // about yet.
1277 // TODO(austin): Bound how big this can get. We tend not to send massive
1278 // data, so we can probably ignore this for a bit.
1279 node_data.channels[m->channel_index].messages.emplace_back(*m);
1280 }
1281 }
1282
1283 messages_.emplace_back(std::move(*m));
1284 return true;
1285}
1286
1287std::string TimestampMapper::DebugString() const {
1288 std::stringstream ss;
1289 ss << "node " << node() << " [\n";
1290 for (const Message &message : messages_) {
1291 ss << " " << message << "\n";
1292 }
1293 ss << "] queued_until " << queued_until_;
1294 for (const NodeData &ns : nodes_data_) {
1295 if (ns.peer == nullptr) continue;
1296 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1297 size_t channel_index = 0;
1298 for (const NodeData::ChannelData &channel_data :
1299 ns.peer->nodes_data_[node()].channels) {
1300 if (channel_data.messages.empty()) {
1301 continue;
1302 }
Austin Schuhb000de62020-12-03 22:00:40 -08001303
Austin Schuhd2f96102020-12-01 20:27:29 -08001304 ss << " channel " << channel_index << " [\n";
1305 for (const Message &m : channel_data.messages) {
1306 ss << " " << m << "\n";
1307 }
1308 ss << " ]\n";
1309 ++channel_index;
1310 }
1311 ss << "] queued_until " << ns.peer->queued_until_;
1312 }
1313 return ss.str();
1314}
1315
Austin Schuhee711052020-08-24 16:06:09 -07001316std::string MaybeNodeName(const Node *node) {
1317 if (node != nullptr) {
1318 return node->name()->str() + " ";
1319 }
1320 return "";
1321}
1322
Brian Silvermanf51499a2020-09-21 12:49:08 -07001323} // namespace aos::logger