blob: d8e504f908057bbae4197ac27e8ff9eccd2b5133 [file] [log] [blame]
James Kuszmaul38735e82019-12-07 16:42:06 -08001#include "aos/events/logging/logger.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -08002
3#include <fcntl.h>
4#include <sys/stat.h>
5#include <sys/types.h>
6#include <sys/uio.h>
7#include <vector>
8
9#include "absl/strings/string_view.h"
10#include "absl/types/span.h"
11#include "aos/events/event_loop.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080012#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080013#include "aos/flatbuffer_merge.h"
14#include "aos/time/time.h"
15#include "flatbuffers/flatbuffers.h"
16
17DEFINE_int32(flush_size, 1000000,
18 "Number of outstanding bytes to allow before flushing to disk.");
19
20namespace aos {
21namespace logger {
22
23namespace chrono = std::chrono;
24
25DetachedBufferWriter::DetachedBufferWriter(absl::string_view filename)
26 : fd_(open(std::string(filename).c_str(),
27 O_RDWR | O_CLOEXEC | O_CREAT | O_EXCL, 0774)) {
28 PCHECK(fd_ != -1) << ": Failed to open " << filename;
29}
30
31DetachedBufferWriter::~DetachedBufferWriter() {
32 Flush();
33 PLOG_IF(ERROR, close(fd_) == -1) << " Failed to close logfile";
34}
35
36void DetachedBufferWriter::QueueSizedFlatbuffer(
37 flatbuffers::FlatBufferBuilder *fbb) {
38 QueueSizedFlatbuffer(fbb->Release());
39}
40
41void DetachedBufferWriter::QueueSizedFlatbuffer(
42 flatbuffers::DetachedBuffer &&buffer) {
43 queued_size_ += buffer.size();
44 queue_.emplace_back(std::move(buffer));
45
46 if (queued_size_ > static_cast<size_t>(FLAGS_flush_size)) {
47 Flush();
48 }
49}
50
51void DetachedBufferWriter::Flush() {
52 if (queue_.size() == 0u) {
53 return;
54 }
55 iovec_.clear();
56 iovec_.reserve(queue_.size());
57 size_t counted_size = 0;
58 for (size_t i = 0; i < queue_.size(); ++i) {
59 struct iovec n;
60 n.iov_base = queue_[i].data();
61 n.iov_len = queue_[i].size();
62 counted_size += n.iov_len;
63 iovec_.emplace_back(std::move(n));
64 }
65 CHECK_EQ(counted_size, queued_size_);
66 const ssize_t written = writev(fd_, iovec_.data(), iovec_.size());
67
68 PCHECK(written == static_cast<ssize_t>(queued_size_))
69 << ": Wrote " << written << " expected " << queued_size_;
70
71 queued_size_ = 0;
72 queue_.clear();
73 // TODO(austin): Handle partial writes in some way other than crashing...
74}
75
76Logger::Logger(DetachedBufferWriter *writer, EventLoop *event_loop,
77 std::chrono::milliseconds polling_period)
78 : event_loop_(event_loop),
79 writer_(writer),
80 timer_handler_(event_loop_->AddTimer([this]() { DoLogData(); })),
81 polling_period_(polling_period) {
82 for (const Channel *channel : *event_loop_->configuration()->channels()) {
83 FetcherStruct fs;
84 fs.fetcher = event_loop->MakeRawFetcher(channel);
85 fs.written = false;
86 fetchers_.emplace_back(std::move(fs));
87 }
88
89 // When things start, we want to log the header, then the most recent messages
90 // available on each fetcher to capture the previous state, then start
91 // polling.
92 event_loop_->OnRun([this, polling_period]() {
93 // Grab data from each channel right before we declare the log file started
94 // so we can capture the latest message on each channel. This lets us have
95 // non periodic messages with configuration that now get logged.
96 for (FetcherStruct &f : fetchers_) {
97 f.written = !f.fetcher->Fetch();
98 }
99
100 // We need to pick a point in time to declare the log file "started". This
101 // starts here. It needs to be after everything is fetched so that the
102 // fetchers are all pointed at the most recent message before the start
103 // time.
104 const monotonic_clock::time_point monotonic_now =
105 event_loop_->monotonic_now();
106 const realtime_clock::time_point realtime_now = event_loop_->realtime_now();
107 last_synchronized_time_ = monotonic_now;
108
109 {
110 // Now write the header with this timestamp in it.
111 flatbuffers::FlatBufferBuilder fbb;
112 fbb.ForceDefaults(1);
113
114 flatbuffers::Offset<aos::Configuration> configuration_offset =
115 CopyFlatBuffer(event_loop_->configuration(), &fbb);
116
117 aos::logger::LogFileHeader::Builder log_file_header_builder(fbb);
118
119 log_file_header_builder.add_configuration(configuration_offset);
120 // The worst case theoretical out of order is the polling period times 2.
121 // One message could get logged right after the boundary, but be for right
122 // before the next boundary. And the reverse could happen for another
123 // message. Report back 3x to be extra safe, and because the cost isn't
124 // huge on the read side.
125 log_file_header_builder.add_max_out_of_order_duration(
126 std::chrono::duration_cast<std::chrono::nanoseconds>(3 *
127 polling_period)
128 .count());
129
130 log_file_header_builder.add_monotonic_sent_time(
131 std::chrono::duration_cast<std::chrono::nanoseconds>(
132 monotonic_now.time_since_epoch())
133 .count());
134 log_file_header_builder.add_realtime_sent_time(
135 std::chrono::duration_cast<std::chrono::nanoseconds>(
136 realtime_now.time_since_epoch())
137 .count());
138
139 fbb.FinishSizePrefixed(log_file_header_builder.Finish());
140 writer_->QueueSizedFlatbuffer(&fbb);
141 }
142
143 timer_handler_->Setup(event_loop_->monotonic_now() + polling_period,
144 polling_period);
145 });
146}
147
148void Logger::DoLogData() {
149 // We want to guarentee that messages aren't out of order by more than
150 // max_out_of_order_duration. To do this, we need sync points. Every write
151 // cycle should be a sync point.
152 const monotonic_clock::time_point monotonic_now = monotonic_clock::now();
153
154 do {
155 // Move the sync point up by at most polling_period. This forces one sync
156 // per iteration, even if it is small.
157 last_synchronized_time_ =
158 std::min(last_synchronized_time_ + polling_period_, monotonic_now);
159 size_t channel_index = 0;
160 // Write each channel to disk, one at a time.
161 for (FetcherStruct &f : fetchers_) {
162 while (true) {
163 if (f.fetcher.get() == nullptr) {
164 if (!f.fetcher->FetchNext()) {
165 VLOG(1) << "No new data on "
166 << FlatbufferToJson(f.fetcher->channel());
167 break;
168 } else {
169 f.written = false;
170 }
171 }
172
173 if (f.written) {
174 if (!f.fetcher->FetchNext()) {
175 VLOG(1) << "No new data on "
176 << FlatbufferToJson(f.fetcher->channel());
177 break;
178 } else {
179 f.written = false;
180 }
181 }
182
James Kuszmaul91deec92019-12-15 12:18:44 -0800183 CHECK(!f.written);
184
185 // TODO(james): Write tests to exercise this logic.
186 if (f.fetcher->context().monotonic_sent_time <
187 last_synchronized_time_) {
Austin Schuhe309d2a2019-11-29 13:25:21 -0800188 // Write!
189 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
190 max_header_size_);
191 fbb.ForceDefaults(1);
192
193 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset =
194 fbb.CreateVector(
195 static_cast<uint8_t *>(f.fetcher->context().data),
196 f.fetcher->context().size);
197
198 VLOG(1) << "Writing data for channel "
199 << FlatbufferToJson(f.fetcher->channel());
200
201 MessageHeader::Builder message_header_builder(fbb);
202 message_header_builder.add_channel_index(channel_index);
203 message_header_builder.add_monotonic_sent_time(
204 f.fetcher->context()
205 .monotonic_sent_time.time_since_epoch()
206 .count());
207 message_header_builder.add_realtime_sent_time(
208 f.fetcher->context()
209 .realtime_sent_time.time_since_epoch()
210 .count());
211
212 message_header_builder.add_queue_index(
213 f.fetcher->context().queue_index);
214
215 message_header_builder.add_data(data_offset);
216
217 fbb.FinishSizePrefixed(message_header_builder.Finish());
218 max_header_size_ = std::max(
219 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
220 writer_->QueueSizedFlatbuffer(&fbb);
221
222 f.written = true;
James Kuszmaul91deec92019-12-15 12:18:44 -0800223 } else {
224 break;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800225 }
226 }
227
228 ++channel_index;
229 }
230
231 CHECK_EQ(channel_index, fetchers_.size());
232
233 // If we missed cycles, we could be pretty far behind. Spin until we are
234 // caught up.
235 } while (last_synchronized_time_ + polling_period_ < monotonic_now);
236
237 writer_->Flush();
238}
239
240LogReader::LogReader(absl::string_view filename)
241 : fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
242 PCHECK(fd_ != -1) << ": Failed to open " << filename;
243
244 // Make sure we have enough to read the size.
245 absl::Span<const uint8_t> config_data = ReadMessage();
246
247 // Make sure something was read.
248 CHECK(config_data != absl::Span<const uint8_t>());
249
250 // And copy the config so we have it forever.
251 configuration_ = std::vector<uint8_t>(config_data.begin(), config_data.end());
252
253 max_out_of_order_duration_ = std::chrono::nanoseconds(
254 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
255 ->max_out_of_order_duration());
256
257 channels_.resize(configuration()->channels()->size());
258
259 QueueMessages();
260}
261
262bool LogReader::ReadBlock() {
263 if (end_of_file_) {
264 return false;
265 }
266
267 // Appends 256k. This is enough that the read call is efficient. We don't
268 // want to spend too much time reading small chunks because the syscalls for
269 // that will be expensive.
270 constexpr size_t kReadSize = 256 * 1024;
271
272 // Strip off any unused data at the front.
273 if (consumed_data_ != 0) {
274 data_.erase(data_.begin(), data_.begin() + consumed_data_);
275 consumed_data_ = 0;
276 }
277
278 const size_t starting_size = data_.size();
279
280 // This should automatically grow the backing store. It won't shrink if we
281 // get a small chunk later. This reduces allocations when we want to append
282 // more data.
283 data_.resize(data_.size() + kReadSize);
284
285 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
286 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
287 if (count == 0) {
288 end_of_file_ = true;
289 return false;
290 }
291 PCHECK(count > 0);
292
293 return true;
294}
295
296bool LogReader::MessageAvailable() {
297 // Are we big enough to read the size?
298 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
299 return false;
300 }
301
302 // Then, are we big enough to read the full message?
303 const size_t data_size =
304 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
305 sizeof(flatbuffers::uoffset_t);
306 if (data_.size() < consumed_data_ + data_size) {
307 return false;
308 }
309
310 return true;
311}
312
313absl::Span<const uint8_t> LogReader::ReadMessage() {
314 // Make sure we have enough for the size.
315 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
316 if (!ReadBlock()) {
317 return absl::Span<const uint8_t>();
318 }
319 }
320
321 // Now make sure we have enough for the message.
322 const size_t data_size =
323 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
324 sizeof(flatbuffers::uoffset_t);
325 while (data_.size() < consumed_data_ + data_size) {
326 if (!ReadBlock()) {
327 return absl::Span<const uint8_t>();
328 }
329 }
330
331 // And return it, consuming the data.
332 const uint8_t *data_ptr = data_.data() + consumed_data_;
333
334 consumed_data_ += data_size;
335
336 return absl::Span<const uint8_t>(data_ptr, data_size);
337}
338
339void LogReader::QueueMessages() {
340 while (true) {
341 // Don't queue if we have enough data already.
342 // When a log file starts, there should be a message from each channel.
343 // Those messages might be very old. Make sure to read a chunk past the
344 // starting time.
345 if (channel_heap_.size() > 0 &&
346 newest_timestamp_ >
347 std::max(oldest_message().first, monotonic_start_time()) +
348 max_out_of_order_duration_) {
349 break;
350 }
351
352 absl::Span<const uint8_t> msg_data = ReadMessage();
353 if (msg_data == absl::Span<const uint8_t>()) {
354 break;
355 }
356
357 FlatbufferVector<MessageHeader> msg(std::vector<uint8_t>(
358 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end()));
359
360 EmplaceDataBack(std::move(msg));
361 }
362
363 queue_data_time_ = newest_timestamp_ - max_out_of_order_duration_;
364}
365
366const Configuration *LogReader::configuration() {
367 return flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
368 ->configuration();
369}
370
371monotonic_clock::time_point LogReader::monotonic_start_time() {
372 return monotonic_clock::time_point(std::chrono::nanoseconds(
373 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
374 ->monotonic_sent_time()));
375}
376
377realtime_clock::time_point LogReader::realtime_start_time() {
378 return realtime_clock::time_point(std::chrono::nanoseconds(
379 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
380 ->realtime_sent_time()));
381}
382
383void LogReader::Register(EventLoop *event_loop) {
384 event_loop_ = event_loop;
385
Austin Schuh39788ff2019-12-01 18:22:57 -0800386 // Otherwise we replay the timing report and try to resend it...
387 event_loop_->SkipTimingReport();
388
Austin Schuhe309d2a2019-11-29 13:25:21 -0800389 for (size_t i = 0; i < channels_.size(); ++i) {
390 CHECK_EQ(configuration()->channels()->Get(i)->name(),
391 event_loop_->configuration()->channels()->Get(i)->name());
392 CHECK_EQ(configuration()->channels()->Get(i)->type(),
393 event_loop_->configuration()->channels()->Get(i)->type());
394
395 channels_[i].raw_sender = event_loop_->MakeRawSender(
396 event_loop_->configuration()->channels()->Get(i));
397 }
398
399 timer_handler_ = event_loop_->AddTimer([this]() {
400 std::pair<monotonic_clock::time_point, int> oldest_channel_index =
401 PopOldestChannel();
402 const monotonic_clock::time_point monotonic_now =
Austin Schuh39788ff2019-12-01 18:22:57 -0800403 event_loop_->context().monotonic_sent_time;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800404 CHECK(monotonic_now == oldest_channel_index.first)
405 << ": Now " << monotonic_now.time_since_epoch().count()
406 << " trying to send "
407 << oldest_channel_index.first.time_since_epoch().count();
408
409 struct LogReader::ChannelData &channel =
410 channels_[oldest_channel_index.second];
411
412 FlatbufferVector<MessageHeader> front = std::move(channel.front());
413
414 CHECK(front.message().data() != nullptr);
415 if (oldest_channel_index.first > monotonic_start_time()) {
416 channel.raw_sender->Send(front.message().data()->Data(),
417 front.message().data()->size());
418 } else {
419 LOG(WARNING) << "Not sending data from before the start of the log file. "
420 << oldest_channel_index.first.time_since_epoch().count()
421 << " start "
422 << monotonic_start_time().time_since_epoch().count() << " "
423 << FlatbufferToJson(front);
424 }
425 channel.data.pop_front();
426
427 // Re-push it and update the oldest timestamp.
428 if (channel.data.size() != 0) {
429 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
430 chrono::nanoseconds(channel.front().message().monotonic_sent_time()));
431 PushChannelHeap(timestamp, oldest_channel_index.second);
432 channel.oldest_timestamp = timestamp;
433 } else {
434 channel.oldest_timestamp = monotonic_clock::min_time;
435 }
436
437 if (monotonic_now > queue_data_time_) {
438 QueueMessages();
439 }
440
441 if (channel_heap_.size() != 0) {
442 timer_handler_->Setup(oldest_message().first);
443 }
444 });
445
446 if (channel_heap_.size() > 0u) {
447 event_loop_->OnRun(
448 [this]() { timer_handler_->Setup(oldest_message().first); });
449 }
450}
451
452void LogReader::Deregister() {
453 for (size_t i = 0; i < channels_.size(); ++i) {
454 channels_[i].raw_sender.reset();
455 }
456}
457
458void LogReader::EmplaceDataBack(FlatbufferVector<MessageHeader> &&new_data) {
459 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
460 chrono::nanoseconds(new_data.message().monotonic_sent_time()));
461 const size_t channel_index = new_data.message().channel_index();
462 CHECK_LT(channel_index, channels_.size());
463 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
464 if (channels_[channel_index].data.size() == 0) {
465 channels_[channel_index].oldest_timestamp = timestamp;
466 PushChannelHeap(timestamp, channel_index);
467 }
468 channels_[channel_index].data.emplace_back(std::move(new_data));
469}
470
471namespace {
472
473bool ChannelHeapCompare(
474 const std::pair<monotonic_clock::time_point, int> first,
475 const std::pair<monotonic_clock::time_point, int> second) {
476 if (first.first > second.first) {
477 return true;
478 } else if (first.first == second.first) {
479 return first.second > second.second;
480 } else {
481 return false;
482 }
483}
484
485} // namespace
486
487void LogReader::PushChannelHeap(monotonic_clock::time_point timestamp,
488 int channel_index) {
489 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
490
491 // The default sort puts the newest message first. Use a custom comparator to
492 // put the oldest message first.
493 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
494 ChannelHeapCompare);
495}
496
497std::pair<monotonic_clock::time_point, int> LogReader::PopOldestChannel() {
498 std::pair<monotonic_clock::time_point, int> result = channel_heap_.front();
499 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
500 &ChannelHeapCompare);
501 channel_heap_.pop_back();
502 return result;
503}
504
505} // namespace logger
506} // namespace aos