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