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