blob: d39f0a79e22121a537705b3f813b8f357224ec71 [file] [log] [blame]
Austin Schuhe309d2a2019-11-29 13:25:21 -08001#include "aos/events/logger.h"
2
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"
12#include "aos/events/logger_generated.h"
13#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
183 if (!f.written && f.fetcher->context().monotonic_sent_time <
184 last_synchronized_time_) {
185 // Write!
186 flatbuffers::FlatBufferBuilder fbb(f.fetcher->context().size +
187 max_header_size_);
188 fbb.ForceDefaults(1);
189
190 flatbuffers::Offset<flatbuffers::Vector<uint8_t>> data_offset =
191 fbb.CreateVector(
192 static_cast<uint8_t *>(f.fetcher->context().data),
193 f.fetcher->context().size);
194
195 VLOG(1) << "Writing data for channel "
196 << FlatbufferToJson(f.fetcher->channel());
197
198 MessageHeader::Builder message_header_builder(fbb);
199 message_header_builder.add_channel_index(channel_index);
200 message_header_builder.add_monotonic_sent_time(
201 f.fetcher->context()
202 .monotonic_sent_time.time_since_epoch()
203 .count());
204 message_header_builder.add_realtime_sent_time(
205 f.fetcher->context()
206 .realtime_sent_time.time_since_epoch()
207 .count());
208
209 message_header_builder.add_queue_index(
210 f.fetcher->context().queue_index);
211
212 message_header_builder.add_data(data_offset);
213
214 fbb.FinishSizePrefixed(message_header_builder.Finish());
215 max_header_size_ = std::max(
216 max_header_size_, fbb.GetSize() - f.fetcher->context().size);
217 writer_->QueueSizedFlatbuffer(&fbb);
218
219 f.written = true;
220 }
221 }
222
223 ++channel_index;
224 }
225
226 CHECK_EQ(channel_index, fetchers_.size());
227
228 // If we missed cycles, we could be pretty far behind. Spin until we are
229 // caught up.
230 } while (last_synchronized_time_ + polling_period_ < monotonic_now);
231
232 writer_->Flush();
233}
234
235LogReader::LogReader(absl::string_view filename)
236 : fd_(open(std::string(filename).c_str(), O_RDONLY | O_CLOEXEC)) {
237 PCHECK(fd_ != -1) << ": Failed to open " << filename;
238
239 // Make sure we have enough to read the size.
240 absl::Span<const uint8_t> config_data = ReadMessage();
241
242 // Make sure something was read.
243 CHECK(config_data != absl::Span<const uint8_t>());
244
245 // And copy the config so we have it forever.
246 configuration_ = std::vector<uint8_t>(config_data.begin(), config_data.end());
247
248 max_out_of_order_duration_ = std::chrono::nanoseconds(
249 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
250 ->max_out_of_order_duration());
251
252 channels_.resize(configuration()->channels()->size());
253
254 QueueMessages();
255}
256
257bool LogReader::ReadBlock() {
258 if (end_of_file_) {
259 return false;
260 }
261
262 // Appends 256k. This is enough that the read call is efficient. We don't
263 // want to spend too much time reading small chunks because the syscalls for
264 // that will be expensive.
265 constexpr size_t kReadSize = 256 * 1024;
266
267 // Strip off any unused data at the front.
268 if (consumed_data_ != 0) {
269 data_.erase(data_.begin(), data_.begin() + consumed_data_);
270 consumed_data_ = 0;
271 }
272
273 const size_t starting_size = data_.size();
274
275 // This should automatically grow the backing store. It won't shrink if we
276 // get a small chunk later. This reduces allocations when we want to append
277 // more data.
278 data_.resize(data_.size() + kReadSize);
279
280 ssize_t count = read(fd_, &data_[starting_size], kReadSize);
281 data_.resize(starting_size + std::max(count, static_cast<ssize_t>(0)));
282 if (count == 0) {
283 end_of_file_ = true;
284 return false;
285 }
286 PCHECK(count > 0);
287
288 return true;
289}
290
291bool LogReader::MessageAvailable() {
292 // Are we big enough to read the size?
293 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
294 return false;
295 }
296
297 // Then, are we big enough to read the full message?
298 const size_t data_size =
299 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
300 sizeof(flatbuffers::uoffset_t);
301 if (data_.size() < consumed_data_ + data_size) {
302 return false;
303 }
304
305 return true;
306}
307
308absl::Span<const uint8_t> LogReader::ReadMessage() {
309 // Make sure we have enough for the size.
310 if (data_.size() - consumed_data_ < sizeof(flatbuffers::uoffset_t)) {
311 if (!ReadBlock()) {
312 return absl::Span<const uint8_t>();
313 }
314 }
315
316 // Now make sure we have enough for the message.
317 const size_t data_size =
318 flatbuffers::GetPrefixedSize(data_.data() + consumed_data_) +
319 sizeof(flatbuffers::uoffset_t);
320 while (data_.size() < consumed_data_ + data_size) {
321 if (!ReadBlock()) {
322 return absl::Span<const uint8_t>();
323 }
324 }
325
326 // And return it, consuming the data.
327 const uint8_t *data_ptr = data_.data() + consumed_data_;
328
329 consumed_data_ += data_size;
330
331 return absl::Span<const uint8_t>(data_ptr, data_size);
332}
333
334void LogReader::QueueMessages() {
335 while (true) {
336 // Don't queue if we have enough data already.
337 // When a log file starts, there should be a message from each channel.
338 // Those messages might be very old. Make sure to read a chunk past the
339 // starting time.
340 if (channel_heap_.size() > 0 &&
341 newest_timestamp_ >
342 std::max(oldest_message().first, monotonic_start_time()) +
343 max_out_of_order_duration_) {
344 break;
345 }
346
347 absl::Span<const uint8_t> msg_data = ReadMessage();
348 if (msg_data == absl::Span<const uint8_t>()) {
349 break;
350 }
351
352 FlatbufferVector<MessageHeader> msg(std::vector<uint8_t>(
353 msg_data.begin() + sizeof(flatbuffers::uoffset_t), msg_data.end()));
354
355 EmplaceDataBack(std::move(msg));
356 }
357
358 queue_data_time_ = newest_timestamp_ - max_out_of_order_duration_;
359}
360
361const Configuration *LogReader::configuration() {
362 return flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
363 ->configuration();
364}
365
366monotonic_clock::time_point LogReader::monotonic_start_time() {
367 return monotonic_clock::time_point(std::chrono::nanoseconds(
368 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
369 ->monotonic_sent_time()));
370}
371
372realtime_clock::time_point LogReader::realtime_start_time() {
373 return realtime_clock::time_point(std::chrono::nanoseconds(
374 flatbuffers::GetSizePrefixedRoot<LogFileHeader>(configuration_.data())
375 ->realtime_sent_time()));
376}
377
378void LogReader::Register(EventLoop *event_loop) {
379 event_loop_ = event_loop;
380
Austin Schuh39788ff2019-12-01 18:22:57 -0800381 // Otherwise we replay the timing report and try to resend it...
382 event_loop_->SkipTimingReport();
383
Austin Schuhe309d2a2019-11-29 13:25:21 -0800384 for (size_t i = 0; i < channels_.size(); ++i) {
385 CHECK_EQ(configuration()->channels()->Get(i)->name(),
386 event_loop_->configuration()->channels()->Get(i)->name());
387 CHECK_EQ(configuration()->channels()->Get(i)->type(),
388 event_loop_->configuration()->channels()->Get(i)->type());
389
390 channels_[i].raw_sender = event_loop_->MakeRawSender(
391 event_loop_->configuration()->channels()->Get(i));
392 }
393
394 timer_handler_ = event_loop_->AddTimer([this]() {
395 std::pair<monotonic_clock::time_point, int> oldest_channel_index =
396 PopOldestChannel();
397 const monotonic_clock::time_point monotonic_now =
Austin Schuh39788ff2019-12-01 18:22:57 -0800398 event_loop_->context().monotonic_sent_time;
Austin Schuhe309d2a2019-11-29 13:25:21 -0800399 CHECK(monotonic_now == oldest_channel_index.first)
400 << ": Now " << monotonic_now.time_since_epoch().count()
401 << " trying to send "
402 << oldest_channel_index.first.time_since_epoch().count();
403
404 struct LogReader::ChannelData &channel =
405 channels_[oldest_channel_index.second];
406
407 FlatbufferVector<MessageHeader> front = std::move(channel.front());
408
409 CHECK(front.message().data() != nullptr);
410 if (oldest_channel_index.first > monotonic_start_time()) {
411 channel.raw_sender->Send(front.message().data()->Data(),
412 front.message().data()->size());
413 } else {
414 LOG(WARNING) << "Not sending data from before the start of the log file. "
415 << oldest_channel_index.first.time_since_epoch().count()
416 << " start "
417 << monotonic_start_time().time_since_epoch().count() << " "
418 << FlatbufferToJson(front);
419 }
420 channel.data.pop_front();
421
422 // Re-push it and update the oldest timestamp.
423 if (channel.data.size() != 0) {
424 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
425 chrono::nanoseconds(channel.front().message().monotonic_sent_time()));
426 PushChannelHeap(timestamp, oldest_channel_index.second);
427 channel.oldest_timestamp = timestamp;
428 } else {
429 channel.oldest_timestamp = monotonic_clock::min_time;
430 }
431
432 if (monotonic_now > queue_data_time_) {
433 QueueMessages();
434 }
435
436 if (channel_heap_.size() != 0) {
437 timer_handler_->Setup(oldest_message().first);
438 }
439 });
440
441 if (channel_heap_.size() > 0u) {
442 event_loop_->OnRun(
443 [this]() { timer_handler_->Setup(oldest_message().first); });
444 }
445}
446
447void LogReader::Deregister() {
448 for (size_t i = 0; i < channels_.size(); ++i) {
449 channels_[i].raw_sender.reset();
450 }
451}
452
453void LogReader::EmplaceDataBack(FlatbufferVector<MessageHeader> &&new_data) {
454 const monotonic_clock::time_point timestamp = monotonic_clock::time_point(
455 chrono::nanoseconds(new_data.message().monotonic_sent_time()));
456 const size_t channel_index = new_data.message().channel_index();
457 CHECK_LT(channel_index, channels_.size());
458 newest_timestamp_ = std::max(newest_timestamp_, timestamp);
459 if (channels_[channel_index].data.size() == 0) {
460 channels_[channel_index].oldest_timestamp = timestamp;
461 PushChannelHeap(timestamp, channel_index);
462 }
463 channels_[channel_index].data.emplace_back(std::move(new_data));
464}
465
466namespace {
467
468bool ChannelHeapCompare(
469 const std::pair<monotonic_clock::time_point, int> first,
470 const std::pair<monotonic_clock::time_point, int> second) {
471 if (first.first > second.first) {
472 return true;
473 } else if (first.first == second.first) {
474 return first.second > second.second;
475 } else {
476 return false;
477 }
478}
479
480} // namespace
481
482void LogReader::PushChannelHeap(monotonic_clock::time_point timestamp,
483 int channel_index) {
484 channel_heap_.push_back(std::make_pair(timestamp, channel_index));
485
486 // The default sort puts the newest message first. Use a custom comparator to
487 // put the oldest message first.
488 std::push_heap(channel_heap_.begin(), channel_heap_.end(),
489 ChannelHeapCompare);
490}
491
492std::pair<monotonic_clock::time_point, int> LogReader::PopOldestChannel() {
493 std::pair<monotonic_clock::time_point, int> result = channel_heap_.front();
494 std::pop_heap(channel_heap_.begin(), channel_heap_.end(),
495 &ChannelHeapCompare);
496 channel_heap_.pop_back();
497 return result;
498}
499
500} // namespace logger
501} // namespace aos