blob: 6d73d67b31ca3b341a038f7c96fbca2ad7c734cd [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__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070020#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070021#elif defined(__aarch64__)
Tyler Chatow2015bc62021-08-04 21:15:09 -070022#define ENABLE_LZMA (!__has_feature(memory_sanitizer))
Brian Silvermanf59fe3f2020-09-22 21:04:09 -070023#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 {
Austin Schuh58646e22021-08-23 23:51:46 -070060 PCHECK(fd_ != -1) << ": Failed to open " << this->filename()
61 << " for writing";
62 VLOG(1) << "Opened " << this->filename() << " for writing";
Brian Silvermana9f2ec92020-10-06 18:00:53 -070063 }
64 }
Austin Schuha36c8902019-12-30 18:07:15 -080065}
66
67DetachedBufferWriter::~DetachedBufferWriter() {
Brian Silverman0465fcf2020-09-24 00:29:18 -070068 Close();
69 if (ran_out_of_space_) {
70 CHECK(acknowledge_ran_out_of_space_)
71 << ": Unacknowledged out of disk space, log file was not completed";
Brian Silvermanf51499a2020-09-21 12:49:08 -070072 }
Austin Schuh2f8fd752020-09-01 22:38:28 -070073}
74
Brian Silvermand90905f2020-09-23 14:42:56 -070075DetachedBufferWriter::DetachedBufferWriter(DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070076 *this = std::move(other);
77}
78
Brian Silverman87ac0402020-09-17 14:47:01 -070079// When other is destroyed "soon" (which it should be because we're getting an
80// rvalue reference to it), it will flush etc all the data we have queued up
81// (because that data will then be its data).
Austin Schuh2f8fd752020-09-01 22:38:28 -070082DetachedBufferWriter &DetachedBufferWriter::operator=(
83 DetachedBufferWriter &&other) {
Austin Schuh2f8fd752020-09-01 22:38:28 -070084 std::swap(filename_, other.filename_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070085 std::swap(encoder_, other.encoder_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070086 std::swap(fd_, other.fd_);
Brian Silverman0465fcf2020-09-24 00:29:18 -070087 std::swap(ran_out_of_space_, other.ran_out_of_space_);
88 std::swap(acknowledge_ran_out_of_space_, other.acknowledge_ran_out_of_space_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070089 std::swap(iovec_, other.iovec_);
Brian Silvermanf51499a2020-09-21 12:49:08 -070090 std::swap(max_write_time_, other.max_write_time_);
91 std::swap(max_write_time_bytes_, other.max_write_time_bytes_);
92 std::swap(max_write_time_messages_, other.max_write_time_messages_);
93 std::swap(total_write_time_, other.total_write_time_);
94 std::swap(total_write_count_, other.total_write_count_);
95 std::swap(total_write_messages_, other.total_write_messages_);
96 std::swap(total_write_bytes_, other.total_write_bytes_);
Austin Schuh2f8fd752020-09-01 22:38:28 -070097 return *this;
Austin Schuha36c8902019-12-30 18:07:15 -080098}
99
Brian Silvermanf51499a2020-09-21 12:49:08 -0700100void DetachedBufferWriter::QueueSpan(absl::Span<const uint8_t> span) {
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700101 if (ran_out_of_space_) {
102 // We don't want any later data to be written after space becomes
103 // available, so refuse to write anything more once we've dropped data
104 // because we ran out of space.
105 VLOG(1) << "Ignoring span: " << span.size();
106 return;
107 }
108
Austin Schuhbd06ae42021-03-31 22:48:21 -0700109 aos::monotonic_clock::time_point now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700110 if (encoder_->may_bypass() && span.size() > 4096u) {
111 // Over this threshold, we'll assume it's cheaper to add an extra
112 // syscall to write the data immediately instead of copying it to
113 // enqueue.
Austin Schuha36c8902019-12-30 18:07:15 -0800114
Brian Silvermanf51499a2020-09-21 12:49:08 -0700115 // First, flush everything.
116 while (encoder_->queue_size() > 0u) {
117 Flush();
118 }
Austin Schuhde031b72020-01-10 19:34:41 -0800119
Brian Silvermanf51499a2020-09-21 12:49:08 -0700120 // Then, write it directly.
121 const auto start = aos::monotonic_clock::now();
122 const ssize_t written = write(fd_, span.data(), span.size());
123 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700124 HandleWriteReturn(written, span.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700125 UpdateStatsForWrite(end - start, written, 1);
Austin Schuhbd06ae42021-03-31 22:48:21 -0700126 now = end;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700127 } else {
128 encoder_->Encode(CopySpanAsDetachedBuffer(span));
Austin Schuhbd06ae42021-03-31 22:48:21 -0700129 now = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800130 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700131
Austin Schuhbd06ae42021-03-31 22:48:21 -0700132 FlushAtThreshold(now);
Austin Schuha36c8902019-12-30 18:07:15 -0800133}
134
Brian Silverman0465fcf2020-09-24 00:29:18 -0700135void DetachedBufferWriter::Close() {
136 if (fd_ == -1) {
137 return;
138 }
139 encoder_->Finish();
140 while (encoder_->queue_size() > 0) {
141 Flush();
142 }
143 if (close(fd_) == -1) {
144 if (errno == ENOSPC) {
145 ran_out_of_space_ = true;
146 } else {
147 PLOG(ERROR) << "Closing log file failed";
148 }
149 }
150 fd_ = -1;
Austin Schuh58646e22021-08-23 23:51:46 -0700151 VLOG(1) << "Closed " << filename();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700152}
153
Austin Schuha36c8902019-12-30 18:07:15 -0800154void DetachedBufferWriter::Flush() {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700155 if (ran_out_of_space_) {
156 // We don't want any later data to be written after space becomes available,
157 // so refuse to write anything more once we've dropped data because we ran
158 // out of space.
Austin Schuha426f1f2021-03-31 22:27:41 -0700159 if (encoder_) {
160 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
161 encoder_->Clear(encoder_->queue().size());
162 } else {
163 VLOG(1) << "No queue to ignore";
164 }
165 return;
166 }
167
168 const auto queue = encoder_->queue();
169 if (queue.empty()) {
Brian Silverman0465fcf2020-09-24 00:29:18 -0700170 return;
171 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700172
Austin Schuha36c8902019-12-30 18:07:15 -0800173 iovec_.clear();
Brian Silvermanf51499a2020-09-21 12:49:08 -0700174 const size_t iovec_size = std::min<size_t>(queue.size(), IOV_MAX);
175 iovec_.resize(iovec_size);
Austin Schuha36c8902019-12-30 18:07:15 -0800176 size_t counted_size = 0;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700177 for (size_t i = 0; i < iovec_size; ++i) {
178 iovec_[i].iov_base = const_cast<uint8_t *>(queue[i].data());
179 iovec_[i].iov_len = queue[i].size();
180 counted_size += iovec_[i].iov_len;
Austin Schuha36c8902019-12-30 18:07:15 -0800181 }
Brian Silvermanf51499a2020-09-21 12:49:08 -0700182
183 const auto start = aos::monotonic_clock::now();
Austin Schuha36c8902019-12-30 18:07:15 -0800184 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
Brian Silvermanf51499a2020-09-21 12:49:08 -0700185 const auto end = aos::monotonic_clock::now();
Brian Silverman0465fcf2020-09-24 00:29:18 -0700186 HandleWriteReturn(written, counted_size);
Brian Silvermanf51499a2020-09-21 12:49:08 -0700187
188 encoder_->Clear(iovec_size);
189
190 UpdateStatsForWrite(end - start, written, iovec_size);
191}
192
Brian Silverman0465fcf2020-09-24 00:29:18 -0700193void DetachedBufferWriter::HandleWriteReturn(ssize_t write_return,
194 size_t write_size) {
195 if (write_return == -1 && errno == ENOSPC) {
196 ran_out_of_space_ = true;
197 return;
198 }
199 PCHECK(write_return >= 0) << ": write failed";
200 if (write_return < static_cast<ssize_t>(write_size)) {
201 // Sometimes this happens instead of ENOSPC. On a real filesystem, this
202 // never seems to happen in any other case. If we ever want to log to a
203 // socket, this will happen more often. However, until we get there, we'll
204 // just assume it means we ran out of space.
205 ran_out_of_space_ = true;
206 return;
207 }
208}
209
Brian Silvermanf51499a2020-09-21 12:49:08 -0700210void DetachedBufferWriter::UpdateStatsForWrite(
211 aos::monotonic_clock::duration duration, ssize_t written, int iovec_size) {
212 if (duration > max_write_time_) {
213 max_write_time_ = duration;
214 max_write_time_bytes_ = written;
215 max_write_time_messages_ = iovec_size;
216 }
217 total_write_time_ += duration;
218 ++total_write_count_;
219 total_write_messages_ += iovec_size;
220 total_write_bytes_ += written;
221}
222
Austin Schuhbd06ae42021-03-31 22:48:21 -0700223void DetachedBufferWriter::FlushAtThreshold(
224 aos::monotonic_clock::time_point now) {
Austin Schuha426f1f2021-03-31 22:27:41 -0700225 if (ran_out_of_space_) {
226 // We don't want any later data to be written after space becomes available,
227 // so refuse to write anything more once we've dropped data because we ran
228 // out of space.
229 if (encoder_) {
230 VLOG(1) << "Ignoring queue: " << encoder_->queue().size();
231 encoder_->Clear(encoder_->queue().size());
232 } else {
233 VLOG(1) << "No queue to ignore";
234 }
235 return;
236 }
237
Austin Schuhbd06ae42021-03-31 22:48:21 -0700238 // We don't want to flush the first time through. Otherwise we will flush as
239 // the log file header might be compressing, defeating any parallelism and
240 // queueing there.
241 if (last_flush_time_ == aos::monotonic_clock::min_time) {
242 last_flush_time_ = now;
243 }
244
Brian Silvermanf51499a2020-09-21 12:49:08 -0700245 // Flush if we are at the max number of iovs per writev, because there's no
246 // point queueing up any more data in memory. Also flush once we have enough
Austin Schuhbd06ae42021-03-31 22:48:21 -0700247 // data queued up or if it has been long enough.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700248 while (encoder_->queued_bytes() > static_cast<size_t>(FLAGS_flush_size) ||
Austin Schuhbd06ae42021-03-31 22:48:21 -0700249 encoder_->queue_size() >= IOV_MAX ||
250 now > last_flush_time_ +
251 chrono::duration_cast<chrono::nanoseconds>(
252 chrono::duration<double>(FLAGS_flush_period))) {
253 last_flush_time_ = now;
Brian Silvermanf51499a2020-09-21 12:49:08 -0700254 Flush();
255 }
Austin Schuha36c8902019-12-30 18:07:15 -0800256}
257
258flatbuffers::Offset<MessageHeader> PackMessage(
259 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
260 int channel_index, LogType log_type) {
261 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset;
262
263 switch (log_type) {
264 case LogType::kLogMessage:
265 case LogType::kLogMessageAndDeliveryTime:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800266 case LogType::kLogRemoteMessage:
Brian Silvermaneaa41d62020-07-08 19:47:35 -0700267 data_offset = fbb->CreateVector(
268 static_cast<const uint8_t *>(context.data), context.size);
Austin Schuha36c8902019-12-30 18:07:15 -0800269 break;
270
271 case LogType::kLogDeliveryTimeOnly:
272 break;
273 }
274
275 MessageHeader::Builder message_header_builder(*fbb);
276 message_header_builder.add_channel_index(channel_index);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800277
278 switch (log_type) {
279 case LogType::kLogRemoteMessage:
280 message_header_builder.add_queue_index(context.remote_queue_index);
281 message_header_builder.add_monotonic_sent_time(
282 context.monotonic_remote_time.time_since_epoch().count());
283 message_header_builder.add_realtime_sent_time(
284 context.realtime_remote_time.time_since_epoch().count());
285 break;
286
287 case LogType::kLogMessage:
288 case LogType::kLogMessageAndDeliveryTime:
289 case LogType::kLogDeliveryTimeOnly:
290 message_header_builder.add_queue_index(context.queue_index);
291 message_header_builder.add_monotonic_sent_time(
292 context.monotonic_event_time.time_since_epoch().count());
293 message_header_builder.add_realtime_sent_time(
294 context.realtime_event_time.time_since_epoch().count());
295 break;
296 }
Austin Schuha36c8902019-12-30 18:07:15 -0800297
298 switch (log_type) {
299 case LogType::kLogMessage:
Austin Schuh6f3babe2020-01-26 20:34:50 -0800300 case LogType::kLogRemoteMessage:
Austin Schuha36c8902019-12-30 18:07:15 -0800301 message_header_builder.add_data(data_offset);
302 break;
303
304 case LogType::kLogMessageAndDeliveryTime:
305 message_header_builder.add_data(data_offset);
306 [[fallthrough]];
307
308 case LogType::kLogDeliveryTimeOnly:
309 message_header_builder.add_monotonic_remote_time(
310 context.monotonic_remote_time.time_since_epoch().count());
311 message_header_builder.add_realtime_remote_time(
312 context.realtime_remote_time.time_since_epoch().count());
313 message_header_builder.add_remote_queue_index(context.remote_queue_index);
314 break;
315 }
316
317 return message_header_builder.Finish();
318}
319
Brian Silvermanf51499a2020-09-21 12:49:08 -0700320SpanReader::SpanReader(std::string_view filename) : filename_(filename) {
Tyler Chatow2015bc62021-08-04 21:15:09 -0700321 decoder_ = std::make_unique<DummyDecoder>(filename);
322
323 static constexpr std::string_view kXz = ".xz";
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700324 if (filename.substr(filename.size() - kXz.size()) == kXz) {
325#if ENABLE_LZMA
Tyler Chatow2015bc62021-08-04 21:15:09 -0700326 decoder_ = std::make_unique<ThreadedLzmaDecoder>(std::move(decoder_));
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700327#else
328 LOG(FATAL) << "Reading xz-compressed files not supported on this platform";
329#endif
Brian Silvermanf59fe3f2020-09-22 21:04:09 -0700330 }
Austin Schuh05b70472020-01-01 17:11:17 -0800331}
332
Austin Schuhcf5f6442021-07-06 10:43:28 -0700333absl::Span<const uint8_t> SpanReader::PeekMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800334 // Make sure we have enough for the size.
335 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
336 if (!ReadBlock()) {
337 return absl::Span<const uint8_t>();
338 }
339 }
340
341 // Now make sure we have enough for the message.
342 const size_t data_size =
343 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
344 sizeof(flatbuffers::uoffset_t);
Austin Schuhe4fca832020-03-07 16:58:53 -0800345 if (data_size == sizeof(flatbuffers::uoffset_t)) {
346 LOG(ERROR) << "Size of data is zero. Log file end is corrupted, skipping.";
347 LOG(ERROR) << " Rest of log file is "
348 << absl::BytesToHexString(std::string_view(
349 reinterpret_cast<const char *>(data_.data() +
350 consumed_data_),
351 data_.size() - consumed_data_));
352 return absl::Span<const uint8_t>();
353 }
Austin Schuh05b70472020-01-01 17:11:17 -0800354 while (data_.size() < consumed_data_ + data_size) {
355 if (!ReadBlock()) {
356 return absl::Span<const uint8_t>();
357 }
358 }
359
360 // And return it, consuming the data.
361 const uint8_t *data_ptr = data_.data() + consumed_data_;
362
Austin Schuh05b70472020-01-01 17:11:17 -0800363 return absl::Span<const uint8_t>(data_ptr, data_size);
364}
365
Austin Schuhcf5f6442021-07-06 10:43:28 -0700366void SpanReader::ConsumeMessage() {
367 consumed_data_ +=
368 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
369 sizeof(flatbuffers::uoffset_t);
370}
371
372absl::Span<const uint8_t> SpanReader::ReadMessage() {
373 absl::Span<const uint8_t> result = PeekMessage();
374 if (result != absl::Span<const uint8_t>()) {
375 ConsumeMessage();
376 }
377 return result;
378}
379
Austin Schuh05b70472020-01-01 17:11:17 -0800380bool SpanReader::ReadBlock() {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700381 // This is the amount of data we grab at a time. Doing larger chunks minimizes
382 // syscalls and helps decompressors batch things more efficiently.
Austin Schuh05b70472020-01-01 17:11:17 -0800383 constexpr size_t kReadSize = 256 * 1024;
384
385 // Strip off any unused data at the front.
386 if (consumed_data_ != 0) {
Brian Silvermanf51499a2020-09-21 12:49:08 -0700387 data_.erase_front(consumed_data_);
Austin Schuh05b70472020-01-01 17:11:17 -0800388 consumed_data_ = 0;
389 }
390
391 const size_t starting_size = data_.size();
392
393 // This should automatically grow the backing store. It won't shrink if we
394 // get a small chunk later. This reduces allocations when we want to append
395 // more data.
Brian Silvermanf51499a2020-09-21 12:49:08 -0700396 data_.resize(starting_size + kReadSize);
Austin Schuh05b70472020-01-01 17:11:17 -0800397
Brian Silvermanf51499a2020-09-21 12:49:08 -0700398 const size_t count =
399 decoder_->Read(data_.begin() + starting_size, data_.end());
400 data_.resize(starting_size + count);
Austin Schuh05b70472020-01-01 17:11:17 -0800401 if (count == 0) {
Austin Schuh05b70472020-01-01 17:11:17 -0800402 return false;
403 }
Austin Schuh05b70472020-01-01 17:11:17 -0800404
405 return true;
406}
407
Austin Schuhadd6eb32020-11-09 21:24:26 -0800408std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
Austin Schuh0e8db662021-07-06 10:43:47 -0700409 SpanReader *span_reader) {
410 absl::Span<const uint8_t> config_data = span_reader->ReadMessage();
Austin Schuh6f3babe2020-01-26 20:34:50 -0800411
412 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800413 if (config_data == absl::Span<const uint8_t>()) {
414 return std::nullopt;
415 }
Austin Schuh6f3babe2020-01-26 20:34:50 -0800416
Austin Schuh5212cad2020-09-09 23:12:09 -0700417 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700418 SizePrefixedFlatbufferVector<LogFileHeader> result(config_data);
Austin Schuhe09beb12020-12-11 20:04:27 -0800419 if (!result.Verify()) {
420 return std::nullopt;
421 }
Austin Schuh0e8db662021-07-06 10:43:47 -0700422
423 if (FLAGS_workaround_double_headers) {
424 while (true) {
425 absl::Span<const uint8_t> maybe_header_data = span_reader->PeekMessage();
426 if (maybe_header_data == absl::Span<const uint8_t>()) {
427 break;
428 }
429
430 aos::SizePrefixedFlatbufferSpan<aos::logger::LogFileHeader> maybe_header(
431 maybe_header_data);
432 if (maybe_header.Verify()) {
433 LOG(WARNING) << "Found duplicate LogFileHeader in "
434 << span_reader->filename();
435 ResizeableBuffer header_data_copy;
436 header_data_copy.resize(maybe_header_data.size());
437 memcpy(header_data_copy.data(), maybe_header_data.begin(),
438 header_data_copy.size());
439 result = SizePrefixedFlatbufferVector<LogFileHeader>(
440 std::move(header_data_copy));
441
442 span_reader->ConsumeMessage();
443 } else {
444 break;
445 }
446 }
447 }
Austin Schuhe09beb12020-12-11 20:04:27 -0800448 return result;
Austin Schuh6f3babe2020-01-26 20:34:50 -0800449}
450
Austin Schuh0e8db662021-07-06 10:43:47 -0700451std::optional<SizePrefixedFlatbufferVector<LogFileHeader>> ReadHeader(
452 std::string_view filename) {
453 SpanReader span_reader(filename);
454 return ReadHeader(&span_reader);
455}
456
Austin Schuhadd6eb32020-11-09 21:24:26 -0800457std::optional<SizePrefixedFlatbufferVector<MessageHeader>> ReadNthMessage(
Austin Schuh3bd4c402020-11-06 18:19:06 -0800458 std::string_view filename, size_t n) {
Austin Schuh5212cad2020-09-09 23:12:09 -0700459 SpanReader span_reader(filename);
460 absl::Span<const uint8_t> data_span = span_reader.ReadMessage();
461 for (size_t i = 0; i < n + 1; ++i) {
462 data_span = span_reader.ReadMessage();
463
464 // Make sure something was read.
Austin Schuh3bd4c402020-11-06 18:19:06 -0800465 if (data_span == absl::Span<const uint8_t>()) {
466 return std::nullopt;
467 }
Austin Schuh5212cad2020-09-09 23:12:09 -0700468 }
469
Brian Silverman354697a2020-09-22 21:06:32 -0700470 // And copy the config so we have it forever, removing the size prefix.
Austin Schuhb929c4e2021-07-12 15:32:53 -0700471 SizePrefixedFlatbufferVector<MessageHeader> result(data_span);
Austin Schuhe09beb12020-12-11 20:04:27 -0800472 if (!result.Verify()) {
473 return std::nullopt;
474 }
475 return result;
Austin Schuh5212cad2020-09-09 23:12:09 -0700476}
477
Austin Schuh05b70472020-01-01 17:11:17 -0800478MessageReader::MessageReader(std::string_view filename)
Austin Schuh97789fc2020-08-01 14:42:45 -0700479 : span_reader_(filename),
Austin Schuhadd6eb32020-11-09 21:24:26 -0800480 raw_log_file_header_(
481 SizePrefixedFlatbufferVector<LogFileHeader>::Empty()) {
Austin Schuh0e8db662021-07-06 10:43:47 -0700482 std::optional<SizePrefixedFlatbufferVector<LogFileHeader>>
483 raw_log_file_header = ReadHeader(&span_reader_);
Austin Schuh05b70472020-01-01 17:11:17 -0800484
485 // Make sure something was read.
Austin Schuh0e8db662021-07-06 10:43:47 -0700486 CHECK(raw_log_file_header) << ": Failed to read header from: " << filename;
Austin Schuh05b70472020-01-01 17:11:17 -0800487
Austin Schuh0e8db662021-07-06 10:43:47 -0700488 raw_log_file_header_ = std::move(*raw_log_file_header);
Austin Schuh05b70472020-01-01 17:11:17 -0800489
Austin Schuh5b728b72021-06-16 14:57:15 -0700490 CHECK(raw_log_file_header_.Verify()) << "Log file header is corrupted";
491
Austin Schuhcde938c2020-02-02 17:30:07 -0800492 max_out_of_order_duration_ =
Austin Schuha040c3f2021-02-13 16:09:07 -0800493 FLAGS_max_out_of_order > 0
494 ? chrono::duration_cast<chrono::nanoseconds>(
495 chrono::duration<double>(FLAGS_max_out_of_order))
496 : chrono::nanoseconds(log_file_header()->max_out_of_order_duration());
Austin Schuhcde938c2020-02-02 17:30:07 -0800497
498 VLOG(1) << "Opened " << filename << " as node "
499 << FlatbufferToJson(log_file_header()->node());
Austin Schuh05b70472020-01-01 17:11:17 -0800500}
501
Austin Schuhadd6eb32020-11-09 21:24:26 -0800502std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
503MessageReader::ReadMessage() {
Austin Schuh05b70472020-01-01 17:11:17 -0800504 absl::Span<const uint8_t> msg_data = span_reader_.ReadMessage();
505 if (msg_data == absl::Span<const uint8_t>()) {
506 return std::nullopt;
507 }
508
Austin Schuhb929c4e2021-07-12 15:32:53 -0700509 SizePrefixedFlatbufferVector<MessageHeader> result(msg_data);
Austin Schuh05b70472020-01-01 17:11:17 -0800510
Austin Schuh0e8db662021-07-06 10:43:47 -0700511 CHECK(result.Verify()) << ": Corrupted message from " << filename();
512
Austin Schuh05b70472020-01-01 17:11:17 -0800513 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
514 chrono::nanoseconds(result.message().monotonic_sent_time()));
515
516 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
Austin Schuh8bd96322020-02-13 21:18:22 -0800517 VLOG(2) << "Read from " << filename() << " data " << FlatbufferToJson(result);
Austin Schuh6f3babe2020-01-26 20:34:50 -0800518 return std::move(result);
Austin Schuh05b70472020-01-01 17:11:17 -0800519}
520
Austin Schuhc41603c2020-10-11 16:17:37 -0700521PartsMessageReader::PartsMessageReader(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700522 : parts_(std::move(log_parts)), message_reader_(parts_.parts[0]) {
523 ComputeBootCounts();
524}
525
526void PartsMessageReader::ComputeBootCounts() {
527 boot_counts_.assign(configuration::NodesCount(parts_.config.get()),
528 std::nullopt);
529
530 // We have 3 vintages of log files with different amounts of information.
531 if (log_file_header()->has_boot_uuids()) {
532 // The new hotness with the boots explicitly listed out. We can use the log
533 // file header to compute the boot count of all relevant nodes.
534 CHECK_EQ(log_file_header()->boot_uuids()->size(), boot_counts_.size());
535 size_t node_index = 0;
536 for (const flatbuffers::String *boot_uuid :
537 *log_file_header()->boot_uuids()) {
538 CHECK(parts_.boots);
539 if (boot_uuid->size() != 0) {
540 auto it = parts_.boots->boot_count_map.find(boot_uuid->str());
541 if (it != parts_.boots->boot_count_map.end()) {
542 boot_counts_[node_index] = it->second;
543 }
544 } else if (parts().boots->boots[node_index].size() == 1u) {
545 boot_counts_[node_index] = 0;
546 }
547 ++node_index;
548 }
549 } else {
550 // Older multi-node logs which are guarenteed to have UUIDs logged, or
551 // single node log files with boot UUIDs in the header. We only know how to
552 // order certain boots in certain circumstances.
553 if (configuration::MultiNode(parts_.config.get()) || parts_.boots) {
554 for (size_t node_index = 0; node_index < boot_counts_.size();
555 ++node_index) {
556 CHECK(parts_.boots);
557 if (parts().boots->boots[node_index].size() == 1u) {
558 boot_counts_[node_index] = 0;
559 }
560 }
561 } else {
562 // Really old single node logs without any UUIDs. They can't reboot.
563 CHECK_EQ(boot_counts_.size(), 1u);
564 boot_counts_[0] = 0u;
565 }
566 }
567}
Austin Schuhc41603c2020-10-11 16:17:37 -0700568
Austin Schuhadd6eb32020-11-09 21:24:26 -0800569std::optional<SizePrefixedFlatbufferVector<MessageHeader>>
Austin Schuhc41603c2020-10-11 16:17:37 -0700570PartsMessageReader::ReadMessage() {
571 while (!done_) {
Austin Schuhadd6eb32020-11-09 21:24:26 -0800572 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> message =
Austin Schuhc41603c2020-10-11 16:17:37 -0700573 message_reader_.ReadMessage();
574 if (message) {
575 newest_timestamp_ = message_reader_.newest_timestamp();
Austin Schuh32f68492020-11-08 21:45:51 -0800576 const monotonic_clock::time_point monotonic_sent_time(
577 chrono::nanoseconds(message->message().monotonic_sent_time()));
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800578 // TODO(austin): Does this work with startup? Might need to use the start
579 // time.
580 // TODO(austin): Does this work with startup when we don't know the remote
581 // start time too? Look at one of those logs to compare.
Austin Schuh315b96b2020-12-11 21:21:12 -0800582 if (monotonic_sent_time >
583 parts_.monotonic_start_time + max_out_of_order_duration()) {
584 after_start_ = true;
585 }
586 if (after_start_) {
Austin Schuhb000de62020-12-03 22:00:40 -0800587 CHECK_GE(monotonic_sent_time,
588 newest_timestamp_ - max_out_of_order_duration())
Austin Schuha040c3f2021-02-13 16:09:07 -0800589 << ": Max out of order of " << max_out_of_order_duration().count()
590 << "ns exceeded. " << parts_ << ", start time is "
Austin Schuh315b96b2020-12-11 21:21:12 -0800591 << parts_.monotonic_start_time << " currently reading "
592 << filename();
Austin Schuhb000de62020-12-03 22:00:40 -0800593 }
Austin Schuhc41603c2020-10-11 16:17:37 -0700594 return message;
595 }
596 NextLog();
597 }
Austin Schuh32f68492020-11-08 21:45:51 -0800598 newest_timestamp_ = monotonic_clock::max_time;
Austin Schuhc41603c2020-10-11 16:17:37 -0700599 return std::nullopt;
600}
601
602void PartsMessageReader::NextLog() {
603 if (next_part_index_ == parts_.parts.size()) {
604 done_ = true;
605 return;
606 }
607 message_reader_ = MessageReader(parts_.parts[next_part_index_]);
Austin Schuh48507722021-07-17 17:29:24 -0700608 ComputeBootCounts();
Austin Schuhc41603c2020-10-11 16:17:37 -0700609 ++next_part_index_;
610}
611
Austin Schuh1be0ce42020-11-29 22:43:26 -0800612bool Message::operator<(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700613 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700614
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700615 if (this->timestamp.time < m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800616 return true;
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700617 } else if (this->timestamp.time > m2.timestamp.time) {
Austin Schuh1be0ce42020-11-29 22:43:26 -0800618 return false;
619 }
620
621 if (this->channel_index < m2.channel_index) {
622 return true;
623 } else if (this->channel_index > m2.channel_index) {
624 return false;
625 }
626
627 return this->queue_index < m2.queue_index;
628}
629
630bool Message::operator>=(const Message &m2) const { return !(*this < m2); }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800631bool Message::operator==(const Message &m2) const {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700632 CHECK_EQ(this->timestamp.boot, m2.timestamp.boot);
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700633
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700634 return timestamp.time == m2.timestamp.time &&
635 channel_index == m2.channel_index && queue_index == m2.queue_index;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800636}
Austin Schuh1be0ce42020-11-29 22:43:26 -0800637
638std::ostream &operator<<(std::ostream &os, const Message &m) {
639 os << "{.channel_index=" << m.channel_index
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700640 << ", .queue_index=" << m.queue_index << ", .timestamp=" << m.timestamp;
Austin Schuhd2f96102020-12-01 20:27:29 -0800641 if (m.data.Verify()) {
642 os << ", .data="
643 << aos::FlatbufferToJson(m.data,
644 {.multi_line = false, .max_vector_size = 1});
645 }
646 os << "}";
647 return os;
648}
649
650std::ostream &operator<<(std::ostream &os, const TimestampedMessage &m) {
651 os << "{.channel_index=" << m.channel_index
652 << ", .queue_index=" << m.queue_index
653 << ", .monotonic_event_time=" << m.monotonic_event_time
654 << ", .realtime_event_time=" << m.realtime_event_time;
Austin Schuh58646e22021-08-23 23:51:46 -0700655 if (m.remote_queue_index != BootQueueIndex::Invalid()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800656 os << ", .remote_queue_index=" << m.remote_queue_index;
657 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700658 if (m.monotonic_remote_time != BootTimestamp::min_time()) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800659 os << ", .monotonic_remote_time=" << m.monotonic_remote_time;
660 }
661 if (m.realtime_remote_time != realtime_clock::min_time) {
662 os << ", .realtime_remote_time=" << m.realtime_remote_time;
663 }
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700664 if (m.monotonic_timestamp_time != BootTimestamp::min_time()) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800665 os << ", .monotonic_timestamp_time=" << m.monotonic_timestamp_time;
666 }
Austin Schuhd2f96102020-12-01 20:27:29 -0800667 if (m.data.Verify()) {
668 os << ", .data="
669 << aos::FlatbufferToJson(m.data,
670 {.multi_line = false, .max_vector_size = 1});
671 }
672 os << "}";
Austin Schuh1be0ce42020-11-29 22:43:26 -0800673 return os;
674}
675
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800676LogPartsSorter::LogPartsSorter(LogParts log_parts)
Austin Schuh48507722021-07-17 17:29:24 -0700677 : parts_message_reader_(log_parts),
678 source_node_index_(configuration::SourceNodeIndex(parts().config.get())) {
679}
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800680
681Message *LogPartsSorter::Front() {
682 // Queue up data until enough data has been queued that the front message is
683 // sorted enough to be safe to pop. This may do nothing, so we should make
684 // sure the nothing path is checked quickly.
685 if (sorted_until() != monotonic_clock::max_time) {
686 while (true) {
Austin Schuh48507722021-07-17 17:29:24 -0700687 if (!messages_.empty() &&
688 messages_.begin()->timestamp.time < sorted_until() &&
Austin Schuhb000de62020-12-03 22:00:40 -0800689 sorted_until() >= monotonic_start_time()) {
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800690 break;
691 }
692
693 std::optional<SizePrefixedFlatbufferVector<MessageHeader>> m =
694 parts_message_reader_.ReadMessage();
695 // No data left, sorted forever, work through what is left.
696 if (!m) {
697 sorted_until_ = monotonic_clock::max_time;
698 break;
699 }
700
Austin Schuh48507722021-07-17 17:29:24 -0700701 size_t monotonic_timestamp_boot = 0;
702 if (m.value().message().has_monotonic_timestamp_time()) {
703 monotonic_timestamp_boot = parts().logger_boot_count;
704 }
705 size_t monotonic_remote_boot = 0xffffff;
706
707 if (m.value().message().has_monotonic_remote_time()) {
milind-ua50344f2021-08-25 18:22:20 -0700708 const Node *node = parts().config->nodes()->Get(
709 source_node_index_[m->message().channel_index()]);
710
Austin Schuh48507722021-07-17 17:29:24 -0700711 std::optional<size_t> boot = parts_message_reader_.boot_count(
712 source_node_index_[m->message().channel_index()]);
milind-ua50344f2021-08-25 18:22:20 -0700713 CHECK(boot) << ": Failed to find boot for node " << MaybeNodeName(node)
714 << ", with index "
Austin Schuh48507722021-07-17 17:29:24 -0700715 << source_node_index_[m->message().channel_index()];
716 monotonic_remote_boot = *boot;
717 }
718
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700719 messages_.insert(Message{
720 .channel_index = m.value().message().channel_index(),
Austin Schuh58646e22021-08-23 23:51:46 -0700721 .queue_index =
722 BootQueueIndex{.boot = parts().boot_count,
723 .index = m.value().message().queue_index()},
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700724 .timestamp =
725 BootTimestamp{
726 .boot = parts().boot_count,
727 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
728 m.value().message().monotonic_sent_time()))},
Austin Schuh48507722021-07-17 17:29:24 -0700729 .monotonic_remote_boot = monotonic_remote_boot,
730 .monotonic_timestamp_boot = monotonic_timestamp_boot,
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700731 .data = std::move(m.value())});
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800732
733 // Now, update sorted_until_ to match the new message.
734 if (parts_message_reader_.newest_timestamp() >
735 monotonic_clock::min_time +
736 parts_message_reader_.max_out_of_order_duration()) {
737 sorted_until_ = parts_message_reader_.newest_timestamp() -
738 parts_message_reader_.max_out_of_order_duration();
739 } else {
740 sorted_until_ = monotonic_clock::min_time;
741 }
742 }
743 }
744
745 // Now that we have enough data queued, return a pointer to the oldest piece
746 // of data if it exists.
747 if (messages_.empty()) {
Austin Schuhb000de62020-12-03 22:00:40 -0800748 last_message_time_ = monotonic_clock::max_time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800749 return nullptr;
750 }
751
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700752 CHECK_GE(messages_.begin()->timestamp.time, last_message_time_)
Austin Schuh315b96b2020-12-11 21:21:12 -0800753 << DebugString() << " reading " << parts_message_reader_.filename();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700754 last_message_time_ = messages_.begin()->timestamp.time;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800755 return &(*messages_.begin());
756}
757
758void LogPartsSorter::PopFront() { messages_.erase(messages_.begin()); }
759
760std::string LogPartsSorter::DebugString() const {
761 std::stringstream ss;
762 ss << "messages: [\n";
Austin Schuh315b96b2020-12-11 21:21:12 -0800763 int count = 0;
764 bool no_dots = true;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800765 for (const Message &m : messages_) {
Austin Schuh315b96b2020-12-11 21:21:12 -0800766 if (count < 15 || count > static_cast<int>(messages_.size()) - 15) {
767 ss << m << "\n";
768 } else if (no_dots) {
769 ss << "...\n";
770 no_dots = false;
771 }
772 ++count;
Austin Schuh4b5c22a2020-11-30 22:58:43 -0800773 }
774 ss << "] <- " << parts_message_reader_.filename();
775 return ss.str();
776}
777
Austin Schuhd2f96102020-12-01 20:27:29 -0800778NodeMerger::NodeMerger(std::vector<LogParts> parts) {
779 CHECK_GE(parts.size(), 1u);
Austin Schuh715adc12021-06-29 22:07:39 -0700780 // Enforce that we are sorting things only from a single node from a single
781 // boot.
782 const std::string_view part0_node = parts[0].node;
783 const std::string_view part0_source_boot_uuid = parts[0].source_boot_uuid;
Austin Schuhd2f96102020-12-01 20:27:29 -0800784 for (size_t i = 1; i < parts.size(); ++i) {
785 CHECK_EQ(part0_node, parts[i].node) << ": Can't merge different nodes.";
Austin Schuh715adc12021-06-29 22:07:39 -0700786 CHECK_EQ(part0_source_boot_uuid, parts[i].source_boot_uuid)
787 << ": Can't merge different boots.";
Austin Schuhd2f96102020-12-01 20:27:29 -0800788 }
Austin Schuh715adc12021-06-29 22:07:39 -0700789
790 node_ = configuration::GetNodeIndex(parts[0].config.get(), part0_node);
791
Austin Schuhd2f96102020-12-01 20:27:29 -0800792 for (LogParts &part : parts) {
793 parts_sorters_.emplace_back(std::move(part));
794 }
795
Austin Schuhd2f96102020-12-01 20:27:29 -0800796 monotonic_start_time_ = monotonic_clock::max_time;
797 realtime_start_time_ = realtime_clock::max_time;
798 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
799 if (parts_sorter.monotonic_start_time() < monotonic_start_time_) {
800 monotonic_start_time_ = parts_sorter.monotonic_start_time();
801 realtime_start_time_ = parts_sorter.realtime_start_time();
802 }
803 }
804}
Austin Schuh8f52ed52020-11-30 23:12:39 -0800805
Austin Schuh0ca51f32020-12-25 21:51:45 -0800806std::vector<const LogParts *> NodeMerger::Parts() const {
807 std::vector<const LogParts *> p;
808 p.reserve(parts_sorters_.size());
809 for (const LogPartsSorter &parts_sorter : parts_sorters_) {
810 p.emplace_back(&parts_sorter.parts());
811 }
812 return p;
813}
814
Austin Schuh8f52ed52020-11-30 23:12:39 -0800815Message *NodeMerger::Front() {
816 // Return the current Front if we have one, otherwise go compute one.
817 if (current_ != nullptr) {
Austin Schuhb000de62020-12-03 22:00:40 -0800818 Message *result = current_->Front();
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700819 CHECK_GE(result->timestamp.time, last_message_time_);
Austin Schuhb000de62020-12-03 22:00:40 -0800820 return result;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800821 }
822
823 // Otherwise, do a simple search for the oldest message, deduplicating any
824 // duplicates.
825 Message *oldest = nullptr;
826 sorted_until_ = monotonic_clock::max_time;
Austin Schuhd2f96102020-12-01 20:27:29 -0800827 for (LogPartsSorter &parts_sorter : parts_sorters_) {
828 Message *m = parts_sorter.Front();
Austin Schuh8f52ed52020-11-30 23:12:39 -0800829 if (!m) {
Austin Schuhd2f96102020-12-01 20:27:29 -0800830 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800831 continue;
832 }
833 if (oldest == nullptr || *m < *oldest) {
834 oldest = m;
Austin Schuhd2f96102020-12-01 20:27:29 -0800835 current_ = &parts_sorter;
Austin Schuh8f52ed52020-11-30 23:12:39 -0800836 } else if (*m == *oldest) {
Austin Schuh8bf1e632021-01-02 22:41:04 -0800837 // Found a duplicate. If there is a choice, we want the one which has the
838 // timestamp time.
839 if (!m->data.message().has_monotonic_timestamp_time()) {
840 parts_sorter.PopFront();
841 } else if (!oldest->data.message().has_monotonic_timestamp_time()) {
842 current_->PopFront();
843 current_ = &parts_sorter;
844 oldest = m;
845 } else {
846 CHECK_EQ(m->data.message().monotonic_timestamp_time(),
847 oldest->data.message().monotonic_timestamp_time());
848 parts_sorter.PopFront();
849 }
Austin Schuh8f52ed52020-11-30 23:12:39 -0800850 }
851
852 // PopFront may change this, so compute it down here.
Austin Schuhd2f96102020-12-01 20:27:29 -0800853 sorted_until_ = std::min(sorted_until_, parts_sorter.sorted_until());
Austin Schuh8f52ed52020-11-30 23:12:39 -0800854 }
855
Austin Schuhb000de62020-12-03 22:00:40 -0800856 if (oldest) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700857 CHECK_GE(oldest->timestamp.time, last_message_time_);
858 last_message_time_ = oldest->timestamp.time;
Austin Schuhb000de62020-12-03 22:00:40 -0800859 } else {
860 last_message_time_ = monotonic_clock::max_time;
861 }
862
Austin Schuh8f52ed52020-11-30 23:12:39 -0800863 // Return the oldest message found. This will be nullptr if nothing was
864 // found, indicating there is nothing left.
865 return oldest;
866}
867
868void NodeMerger::PopFront() {
869 CHECK(current_ != nullptr) << "Popping before calling Front()";
870 current_->PopFront();
871 current_ = nullptr;
872}
873
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700874BootMerger::BootMerger(std::vector<LogParts> files) {
875 std::vector<std::vector<LogParts>> boots;
876
877 // Now, we need to split things out by boot.
878 for (size_t i = 0; i < files.size(); ++i) {
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700879 const size_t boot_count = files[i].boot_count;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700880 if (boot_count + 1 > boots.size()) {
881 boots.resize(boot_count + 1);
882 }
883 boots[boot_count].emplace_back(std::move(files[i]));
884 }
885
886 node_mergers_.reserve(boots.size());
887 for (size_t i = 0; i < boots.size(); ++i) {
Austin Schuh48507722021-07-17 17:29:24 -0700888 VLOG(2) << "Boot " << i;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700889 for (auto &p : boots[i]) {
Austin Schuh48507722021-07-17 17:29:24 -0700890 VLOG(2) << "Part " << p;
Austin Schuhf16ef6a2021-06-30 21:48:17 -0700891 }
892 node_mergers_.emplace_back(
893 std::make_unique<NodeMerger>(std::move(boots[i])));
894 }
895}
896
897Message *BootMerger::Front() {
898 Message *result = node_mergers_[index_]->Front();
899
900 if (result != nullptr) {
901 return result;
902 }
903
904 if (index_ + 1u == node_mergers_.size()) {
905 // At the end of the last node merger, just return.
906 return nullptr;
907 } else {
908 ++index_;
909 return Front();
910 }
911}
912
913void BootMerger::PopFront() { node_mergers_[index_]->PopFront(); }
914
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700915std::vector<const LogParts *> BootMerger::Parts() const {
916 std::vector<const LogParts *> results;
917 for (const std::unique_ptr<NodeMerger> &node_merger : node_mergers_) {
918 std::vector<const LogParts *> node_parts = node_merger->Parts();
919
920 results.insert(results.end(), std::make_move_iterator(node_parts.begin()),
921 std::make_move_iterator(node_parts.end()));
922 }
923
924 return results;
925}
926
Austin Schuhd2f96102020-12-01 20:27:29 -0800927TimestampMapper::TimestampMapper(std::vector<LogParts> parts)
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700928 : boot_merger_(std::move(parts)),
Austin Schuh79b30942021-01-24 22:32:21 -0800929 timestamp_callback_([](TimestampedMessage *) {}) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700930 for (const LogParts *part : boot_merger_.Parts()) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800931 if (!configuration_) {
932 configuration_ = part->config;
933 } else {
934 CHECK_EQ(configuration_.get(), part->config.get());
935 }
936 }
937 const Configuration *config = configuration_.get();
Austin Schuhd2f96102020-12-01 20:27:29 -0800938 // Only fill out nodes_data_ if there are nodes. Otherwise everything gets
939 // pretty simple.
940 if (configuration::MultiNode(config)) {
941 nodes_data_.resize(config->nodes()->size());
942 const Node *my_node = config->nodes()->Get(node());
943 for (size_t node_index = 0; node_index < nodes_data_.size(); ++node_index) {
944 const Node *node = config->nodes()->Get(node_index);
945 NodeData *node_data = &nodes_data_[node_index];
946 node_data->channels.resize(config->channels()->size());
947 // We should save the channel if it is delivered to the node represented
948 // by the NodeData, but not sent by that node. That combo means it is
949 // forwarded.
950 size_t channel_index = 0;
951 node_data->any_delivered = false;
952 for (const Channel *channel : *config->channels()) {
953 node_data->channels[channel_index].delivered =
954 configuration::ChannelIsReadableOnNode(channel, node) &&
Austin Schuhb3dbb6d2021-01-02 17:29:35 -0800955 configuration::ChannelIsSendableOnNode(channel, my_node) &&
956 (my_node != node);
Austin Schuhd2f96102020-12-01 20:27:29 -0800957 node_data->any_delivered = node_data->any_delivered ||
958 node_data->channels[channel_index].delivered;
959 ++channel_index;
960 }
961 }
962
963 for (const Channel *channel : *config->channels()) {
964 source_node_.emplace_back(configuration::GetNodeIndex(
965 config, channel->source_node()->string_view()));
966 }
967 }
968}
969
970void TimestampMapper::AddPeer(TimestampMapper *timestamp_mapper) {
Austin Schuh0ca51f32020-12-25 21:51:45 -0800971 CHECK(configuration::MultiNode(configuration()));
Austin Schuhd2f96102020-12-01 20:27:29 -0800972 CHECK_NE(timestamp_mapper->node(), node());
973 CHECK_LT(timestamp_mapper->node(), nodes_data_.size());
974
975 NodeData *node_data = &nodes_data_[timestamp_mapper->node()];
976 // Only set it if this node delivers to the peer timestamp_mapper. Otherwise
977 // we could needlessly save data.
978 if (node_data->any_delivered) {
Austin Schuh87dd3832021-01-01 23:07:31 -0800979 VLOG(1) << "Registering on node " << node() << " for peer node "
980 << timestamp_mapper->node();
Austin Schuhd2f96102020-12-01 20:27:29 -0800981 CHECK(timestamp_mapper->nodes_data_[node()].peer == nullptr);
982
983 timestamp_mapper->nodes_data_[node()].peer = this;
Austin Schuh36c00932021-07-19 18:13:21 -0700984
985 node_data->save_for_peer = true;
Austin Schuhd2f96102020-12-01 20:27:29 -0800986 }
987}
988
Austin Schuh79b30942021-01-24 22:32:21 -0800989void TimestampMapper::QueueMessage(Message *m) {
990 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -0800991 .channel_index = m->channel_index,
992 .queue_index = m->queue_index,
993 .monotonic_event_time = m->timestamp,
994 .realtime_event_time = aos::realtime_clock::time_point(
995 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
Austin Schuh58646e22021-08-23 23:51:46 -0700996 .remote_queue_index = BootQueueIndex::Invalid(),
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700997 .monotonic_remote_time = BootTimestamp::min_time(),
Austin Schuhd2f96102020-12-01 20:27:29 -0800998 .realtime_remote_time = realtime_clock::min_time,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -0700999 .monotonic_timestamp_time = BootTimestamp::min_time(),
Austin Schuh79b30942021-01-24 22:32:21 -08001000 .data = std::move(m->data)});
Austin Schuhd2f96102020-12-01 20:27:29 -08001001}
1002
1003TimestampedMessage *TimestampMapper::Front() {
1004 // No need to fetch anything new. A previous message still exists.
1005 switch (first_message_) {
1006 case FirstMessage::kNeedsUpdate:
1007 break;
1008 case FirstMessage::kInMessage:
Austin Schuh79b30942021-01-24 22:32:21 -08001009 return &matched_messages_.front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001010 case FirstMessage::kNullptr:
1011 return nullptr;
1012 }
1013
Austin Schuh79b30942021-01-24 22:32:21 -08001014 if (matched_messages_.empty()) {
1015 if (!QueueMatched()) {
1016 first_message_ = FirstMessage::kNullptr;
1017 return nullptr;
1018 }
1019 }
1020 first_message_ = FirstMessage::kInMessage;
1021 return &matched_messages_.front();
1022}
1023
1024bool TimestampMapper::QueueMatched() {
Austin Schuhd2f96102020-12-01 20:27:29 -08001025 if (nodes_data_.empty()) {
1026 // Simple path. We are single node, so there are no timestamps to match!
1027 CHECK_EQ(messages_.size(), 0u);
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001028 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001029 if (!m) {
Austin Schuh79b30942021-01-24 22:32:21 -08001030 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001031 }
Austin Schuh79b30942021-01-24 22:32:21 -08001032 // Enqueue this message into matched_messages_ so we have a place to
1033 // associate remote timestamps, and return it.
1034 QueueMessage(m);
Austin Schuhd2f96102020-12-01 20:27:29 -08001035
Austin Schuh79b30942021-01-24 22:32:21 -08001036 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1037 last_message_time_ = matched_messages_.back().monotonic_event_time;
1038
1039 // We are thin wrapper around node_merger. Call it directly.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001040 boot_merger_.PopFront();
Austin Schuh79b30942021-01-24 22:32:21 -08001041 timestamp_callback_(&matched_messages_.back());
1042 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001043 }
1044
1045 // We need to only add messages to the list so they get processed for messages
1046 // which are delivered. Reuse the flow below which uses messages_ by just
1047 // adding the new message to messages_ and continuing.
1048 if (messages_.empty()) {
1049 if (!Queue()) {
1050 // Found nothing to add, we are out of data!
Austin Schuh79b30942021-01-24 22:32:21 -08001051 return false;
Austin Schuhd2f96102020-12-01 20:27:29 -08001052 }
1053
1054 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001055 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001056 }
1057
1058 Message *m = &(messages_.front());
1059
1060 if (source_node_[m->channel_index] == node()) {
1061 // From us, just forward it on, filling the remote data in as invalid.
Austin Schuh79b30942021-01-24 22:32:21 -08001062 QueueMessage(m);
1063 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1064 last_message_time_ = matched_messages_.back().monotonic_event_time;
1065 messages_.pop_front();
1066 timestamp_callback_(&matched_messages_.back());
1067 return true;
Austin Schuhd2f96102020-12-01 20:27:29 -08001068 } else {
1069 // Got a timestamp, find the matching remote data, match it, and return it.
1070 Message data = MatchingMessageFor(*m);
1071
1072 // Return the data from the remote. The local message only has timestamp
1073 // info which isn't relevant anymore once extracted.
Austin Schuh79b30942021-01-24 22:32:21 -08001074 matched_messages_.emplace_back(TimestampedMessage{
Austin Schuhd2f96102020-12-01 20:27:29 -08001075 .channel_index = m->channel_index,
1076 .queue_index = m->queue_index,
1077 .monotonic_event_time = m->timestamp,
1078 .realtime_event_time = aos::realtime_clock::time_point(
1079 std::chrono::nanoseconds(m->data.message().realtime_sent_time())),
Austin Schuh58646e22021-08-23 23:51:46 -07001080 .remote_queue_index =
1081 BootQueueIndex{.boot = m->monotonic_remote_boot,
1082 .index = m->data.message().remote_queue_index()},
Austin Schuhd2f96102020-12-01 20:27:29 -08001083 .monotonic_remote_time =
Austin Schuh48507722021-07-17 17:29:24 -07001084 {m->monotonic_remote_boot,
1085 monotonic_clock::time_point(std::chrono::nanoseconds(
1086 m->data.message().monotonic_remote_time()))},
Austin Schuhd2f96102020-12-01 20:27:29 -08001087 .realtime_remote_time = realtime_clock::time_point(
1088 std::chrono::nanoseconds(m->data.message().realtime_remote_time())),
Austin Schuh8bf1e632021-01-02 22:41:04 -08001089 .monotonic_timestamp_time =
Austin Schuh48507722021-07-17 17:29:24 -07001090 {m->monotonic_timestamp_boot,
1091 monotonic_clock::time_point(std::chrono::nanoseconds(
1092 m->data.message().monotonic_timestamp_time()))},
Austin Schuh79b30942021-01-24 22:32:21 -08001093 .data = std::move(data.data)});
1094 CHECK_GE(matched_messages_.back().monotonic_event_time, last_message_time_);
1095 last_message_time_ = matched_messages_.back().monotonic_event_time;
1096 // Since messages_ holds the data, drop it.
1097 messages_.pop_front();
1098 timestamp_callback_(&matched_messages_.back());
1099 return true;
1100 }
1101}
1102
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001103void TimestampMapper::QueueUntil(BootTimestamp queue_time) {
Austin Schuh79b30942021-01-24 22:32:21 -08001104 while (last_message_time_ <= queue_time) {
1105 if (!QueueMatched()) {
1106 return;
1107 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001108 }
1109}
1110
Austin Schuhe639ea12021-01-25 13:00:22 -08001111void TimestampMapper::QueueFor(chrono::nanoseconds time_estimation_buffer) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001112 // Note: queueing for time doesn't really work well across boots. So we just
1113 // assume that if you are using this, you only care about the current boot.
1114 //
1115 // TODO(austin): Is that the right concept?
1116 //
Austin Schuhe639ea12021-01-25 13:00:22 -08001117 // Make sure we have something queued first. This makes the end time
1118 // calculation simpler, and is typically what folks want regardless.
1119 if (matched_messages_.empty()) {
1120 if (!QueueMatched()) {
1121 return;
1122 }
1123 }
1124
1125 const aos::monotonic_clock::time_point end_queue_time =
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001126 std::max(monotonic_start_time(
1127 matched_messages_.front().monotonic_event_time.boot),
1128 matched_messages_.front().monotonic_event_time.time) +
Austin Schuhe639ea12021-01-25 13:00:22 -08001129 time_estimation_buffer;
1130
1131 // Place sorted messages on the list until we have
1132 // --time_estimation_buffer_seconds seconds queued up (but queue at least
1133 // until the log starts).
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001134 while (end_queue_time >= last_message_time_.time) {
Austin Schuhe639ea12021-01-25 13:00:22 -08001135 if (!QueueMatched()) {
1136 return;
1137 }
1138 }
1139}
1140
Austin Schuhd2f96102020-12-01 20:27:29 -08001141void TimestampMapper::PopFront() {
1142 CHECK(first_message_ != FirstMessage::kNeedsUpdate);
1143 first_message_ = FirstMessage::kNeedsUpdate;
1144
Austin Schuh79b30942021-01-24 22:32:21 -08001145 matched_messages_.pop_front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001146}
1147
1148Message TimestampMapper::MatchingMessageFor(const Message &message) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001149 // Figure out what queue index we are looking for.
1150 CHECK(message.data.message().has_remote_queue_index());
Austin Schuh58646e22021-08-23 23:51:46 -07001151 const BootQueueIndex remote_queue_index =
1152 BootQueueIndex{.boot = message.monotonic_remote_boot,
1153 .index = message.data.message().remote_queue_index()};
Austin Schuhd2f96102020-12-01 20:27:29 -08001154
1155 CHECK(message.data.message().has_monotonic_remote_time());
1156 CHECK(message.data.message().has_realtime_remote_time());
1157
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001158 const BootTimestamp monotonic_remote_time{
Austin Schuh48507722021-07-17 17:29:24 -07001159 .boot = message.monotonic_remote_boot,
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001160 .time = monotonic_clock::time_point(std::chrono::nanoseconds(
1161 message.data.message().monotonic_remote_time()))};
Austin Schuhd2f96102020-12-01 20:27:29 -08001162 const realtime_clock::time_point realtime_remote_time(
1163 std::chrono::nanoseconds(message.data.message().realtime_remote_time()));
1164
Austin Schuhfecf1d82020-12-19 16:57:28 -08001165 TimestampMapper *peer = nodes_data_[source_node_[message.channel_index]].peer;
1166
1167 // We only register the peers which we have data for. So, if we are being
1168 // asked to pull a timestamp from a peer which doesn't exist, return an empty
1169 // message.
1170 if (peer == nullptr) {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001171 // TODO(austin): Make sure the tests hit all these paths with a boot count
1172 // of 1...
Austin Schuhfecf1d82020-12-19 16:57:28 -08001173 return Message{
1174 .channel_index = message.channel_index,
1175 .queue_index = remote_queue_index,
1176 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001177 .monotonic_remote_boot = 0xffffff,
1178 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhfecf1d82020-12-19 16:57:28 -08001179 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1180 }
1181
1182 // The queue which will have the matching data, if available.
1183 std::deque<Message> *data_queue =
1184 &peer->nodes_data_[node()].channels[message.channel_index].messages;
1185
Austin Schuh79b30942021-01-24 22:32:21 -08001186 peer->QueueUnmatchedUntil(monotonic_remote_time);
Austin Schuhd2f96102020-12-01 20:27:29 -08001187
1188 if (data_queue->empty()) {
1189 return Message{
1190 .channel_index = message.channel_index,
1191 .queue_index = remote_queue_index,
1192 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001193 .monotonic_remote_boot = 0xffffff,
1194 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhd2f96102020-12-01 20:27:29 -08001195 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1196 }
1197
Austin Schuhd2f96102020-12-01 20:27:29 -08001198 if (remote_queue_index < data_queue->front().queue_index ||
1199 remote_queue_index > data_queue->back().queue_index) {
1200 return Message{
1201 .channel_index = message.channel_index,
1202 .queue_index = remote_queue_index,
1203 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001204 .monotonic_remote_boot = 0xffffff,
1205 .monotonic_timestamp_boot = 0xffffff,
Austin Schuhd2f96102020-12-01 20:27:29 -08001206 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1207 }
1208
Austin Schuh993ccb52020-12-12 15:59:32 -08001209 // The algorithm below is constant time with some assumptions. We need there
1210 // to be no missing messages in the data stream. This also assumes a queue
1211 // hasn't wrapped. That is conservative, but should let us get started.
Austin Schuh58646e22021-08-23 23:51:46 -07001212 if (data_queue->back().queue_index.boot ==
1213 data_queue->front().queue_index.boot &&
1214 (data_queue->back().queue_index.index -
1215 data_queue->front().queue_index.index + 1u ==
1216 data_queue->size())) {
1217 CHECK_EQ(remote_queue_index.boot, data_queue->front().queue_index.boot);
Austin Schuh993ccb52020-12-12 15:59:32 -08001218 // Pull the data out and confirm that the timestamps match as expected.
Austin Schuh58646e22021-08-23 23:51:46 -07001219 //
1220 // TODO(austin): Move if not reliable.
1221 Message result = (*data_queue)[remote_queue_index.index -
1222 data_queue->front().queue_index.index];
Austin Schuh993ccb52020-12-12 15:59:32 -08001223
1224 CHECK_EQ(result.timestamp, monotonic_remote_time)
1225 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1226 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1227 result.data.message().realtime_sent_time())),
1228 realtime_remote_time)
1229 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1230 // Now drop the data off the front. We have deduplicated timestamps, so we
1231 // are done. And all the data is in order.
Austin Schuh58646e22021-08-23 23:51:46 -07001232 data_queue->erase(
1233 data_queue->begin(),
1234 data_queue->begin() +
1235 (remote_queue_index.index - data_queue->front().queue_index.index));
Austin Schuh993ccb52020-12-12 15:59:32 -08001236 return result;
1237 } else {
Austin Schuh58646e22021-08-23 23:51:46 -07001238 // TODO(austin): Binary search.
1239 auto it = std::find_if(
1240 data_queue->begin(), data_queue->end(),
1241 [remote_queue_index,
1242 remote_boot = monotonic_remote_time.boot](const Message &m) {
1243 return m.queue_index == remote_queue_index &&
1244 m.timestamp.boot == remote_boot;
1245 });
Austin Schuh993ccb52020-12-12 15:59:32 -08001246 if (it == data_queue->end()) {
1247 return Message{
1248 .channel_index = message.channel_index,
1249 .queue_index = remote_queue_index,
1250 .timestamp = monotonic_remote_time,
Austin Schuh48507722021-07-17 17:29:24 -07001251 .monotonic_remote_boot = 0xffffff,
1252 .monotonic_timestamp_boot = 0xffffff,
Austin Schuh993ccb52020-12-12 15:59:32 -08001253 .data = SizePrefixedFlatbufferVector<MessageHeader>::Empty()};
1254 }
1255
1256 Message result = std::move(*it);
1257
1258 CHECK_EQ(result.timestamp, monotonic_remote_time)
1259 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1260 CHECK_EQ(realtime_clock::time_point(std::chrono::nanoseconds(
1261 result.data.message().realtime_sent_time())),
1262 realtime_remote_time)
1263 << ": Queue index matches, but timestamp doesn't. Please investigate!";
1264
Austin Schuh58646e22021-08-23 23:51:46 -07001265 // TODO(austin): We still go in order, so we can erase from the beginning to
1266 // our iterator minus 1. That'll keep 1 in the queue.
Austin Schuh993ccb52020-12-12 15:59:32 -08001267 data_queue->erase(it);
1268
1269 return result;
1270 }
Austin Schuhd2f96102020-12-01 20:27:29 -08001271}
1272
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001273void TimestampMapper::QueueUnmatchedUntil(BootTimestamp t) {
Austin Schuhd2f96102020-12-01 20:27:29 -08001274 if (queued_until_ > t) {
1275 return;
1276 }
1277 while (true) {
1278 if (!messages_.empty() && messages_.back().timestamp > t) {
1279 queued_until_ = std::max(queued_until_, messages_.back().timestamp);
1280 return;
1281 }
1282
1283 if (!Queue()) {
1284 // Found nothing to add, we are out of data!
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001285 queued_until_ = BootTimestamp::max_time();
Austin Schuhd2f96102020-12-01 20:27:29 -08001286 return;
1287 }
1288
1289 // Now that it has been added (and cannibalized), forget about it upstream.
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001290 boot_merger_.PopFront();
Austin Schuhd2f96102020-12-01 20:27:29 -08001291 }
1292}
1293
1294bool TimestampMapper::Queue() {
Austin Schuh2dc8c7d2021-07-01 17:41:28 -07001295 Message *m = boot_merger_.Front();
Austin Schuhd2f96102020-12-01 20:27:29 -08001296 if (m == nullptr) {
1297 return false;
1298 }
1299 for (NodeData &node_data : nodes_data_) {
1300 if (!node_data.any_delivered) continue;
Austin Schuh36c00932021-07-19 18:13:21 -07001301 if (!node_data.save_for_peer) continue;
Austin Schuhd2f96102020-12-01 20:27:29 -08001302 if (node_data.channels[m->channel_index].delivered) {
1303 // TODO(austin): This copies the data... Probably not worth stressing
1304 // about yet.
1305 // TODO(austin): Bound how big this can get. We tend not to send massive
1306 // data, so we can probably ignore this for a bit.
1307 node_data.channels[m->channel_index].messages.emplace_back(*m);
1308 }
1309 }
1310
1311 messages_.emplace_back(std::move(*m));
1312 return true;
1313}
1314
1315std::string TimestampMapper::DebugString() const {
1316 std::stringstream ss;
1317 ss << "node " << node() << " [\n";
1318 for (const Message &message : messages_) {
1319 ss << " " << message << "\n";
1320 }
1321 ss << "] queued_until " << queued_until_;
1322 for (const NodeData &ns : nodes_data_) {
1323 if (ns.peer == nullptr) continue;
1324 ss << "\nnode " << ns.peer->node() << " remote_data [\n";
1325 size_t channel_index = 0;
1326 for (const NodeData::ChannelData &channel_data :
1327 ns.peer->nodes_data_[node()].channels) {
1328 if (channel_data.messages.empty()) {
1329 continue;
1330 }
Austin Schuhb000de62020-12-03 22:00:40 -08001331
Austin Schuhd2f96102020-12-01 20:27:29 -08001332 ss << " channel " << channel_index << " [\n";
1333 for (const Message &m : channel_data.messages) {
1334 ss << " " << m << "\n";
1335 }
1336 ss << " ]\n";
1337 ++channel_index;
1338 }
1339 ss << "] queued_until " << ns.peer->queued_until_;
1340 }
1341 return ss.str();
1342}
1343
Austin Schuhee711052020-08-24 16:06:09 -07001344std::string MaybeNodeName(const Node *node) {
1345 if (node != nullptr) {
1346 return node->name()->str() + " ";
1347 }
1348 return "";
1349}
1350
Brian Silvermanf51499a2020-09-21 12:49:08 -07001351} // namespace aos::logger