blob: db23767aaa5e7f84dff4e86deb5f9257facc48b8 [file] [log] [blame]
Austin Schuhe309d2a2019-11-29 13:25:21 -08001#ifndef AOS_EVENTS_LOGGER_H_
2#define AOS_EVENTS_LOGGER_H_
3
4#include <deque>
5#include <vector>
6
7#include "absl/strings/string_view.h"
8#include "absl/types/span.h"
9#include "aos/events/event_loop.h"
James Kuszmaul38735e82019-12-07 16:42:06 -080010#include "aos/events/logging/logger_generated.h"
Austin Schuhe309d2a2019-11-29 13:25:21 -080011#include "aos/time/time.h"
12#include "flatbuffers/flatbuffers.h"
13
14namespace aos {
15namespace logger {
16
17// This class manages efficiently writing a sequence of detached buffers to a
18// file. It queues them up and batches the write operation.
19class DetachedBufferWriter {
20 public:
21 DetachedBufferWriter(absl::string_view filename);
22 ~DetachedBufferWriter();
23
24 // TODO(austin): Snappy compress the log file if it ends with .snappy!
25
26 // Queues up a finished FlatBufferBuilder to be written. Steals the detached
27 // buffer from it.
28 void QueueSizedFlatbuffer(flatbuffers::FlatBufferBuilder *fbb);
29 // Queues up a detached buffer directly.
30 void QueueSizedFlatbuffer(flatbuffers::DetachedBuffer &&buffer);
31
32 // Triggers data to be provided to the kernel and written.
33 void Flush();
34
35 private:
36 int fd_ = -1;
37
38 // Size of all the data in the queue.
39 size_t queued_size_ = 0;
40
41 // List of buffers to flush.
42 std::vector<flatbuffers::DetachedBuffer> queue_;
43 // List of iovecs to use with writev. This is a member variable to avoid
44 // churn.
45 std::vector<struct iovec> iovec_;
46};
47
Austin Schuh646b7b82019-12-22 21:38:55 -080048// Packes a message pointed to by the context into a MessageHeader.
49flatbuffers::Offset<MessageHeader> PackMessage(
50 flatbuffers::FlatBufferBuilder *fbb, const Context &context,
51 int channel_index);
52
Austin Schuhe309d2a2019-11-29 13:25:21 -080053// Logs all channels available in the event loop to disk every 100 ms.
54// Start by logging one message per channel to capture any state and
55// configuration that is sent rately on a channel and would affect execution.
56class Logger {
57 public:
58 Logger(DetachedBufferWriter *writer, EventLoop *event_loop,
59 std::chrono::milliseconds polling_period =
60 std::chrono::milliseconds(100));
61
62 private:
63 void DoLogData();
64
65 EventLoop *event_loop_;
66 DetachedBufferWriter *writer_;
67
68 // Structure to track both a fetcher, and if the data fetched has been
69 // written. We may want to delay writing data to disk so that we don't let
70 // data get too far out of order when written to disk so we can avoid making
71 // it too hard to sort when reading.
72 struct FetcherStruct {
73 std::unique_ptr<RawFetcher> fetcher;
74 bool written = false;
75 };
76
77 std::vector<FetcherStruct> fetchers_;
78 TimerHandler *timer_handler_;
79
80 // Period to poll the channels.
81 const std::chrono::milliseconds polling_period_;
82
83 // Last time that data was written for all channels to disk.
84 monotonic_clock::time_point last_synchronized_time_;
85
86 // Max size that the header has consumed. This much extra data will be
87 // reserved in the builder to avoid reallocating.
88 size_t max_header_size_ = 0;
89};
90
91// Replays all the channels in the logfile to the event loop.
92class LogReader {
93 public:
94 LogReader(absl::string_view filename);
95
96 // Registers the timer and senders used to resend the messages from the log
97 // file.
98 void Register(EventLoop *event_loop);
99 // Unregisters the senders.
100 void Deregister();
101
102 // TODO(austin): Remap channels?
103
104 // Returns the configuration from the log file.
105 const Configuration *configuration();
106
107 // Returns the starting timestamp for the log file.
108 monotonic_clock::time_point monotonic_start_time();
109 realtime_clock::time_point realtime_start_time();
110
111 // TODO(austin): Add the ability to re-publish the fetched messages. Add 2
112 // options, one which publishes them *now*, and another which publishes them
113 // to the simulated event loop factory back in time where they actually
114 // happened.
115
116 private:
117 // Reads a chunk of data into data_. Returns false if no data was read.
118 bool ReadBlock();
119
120 // Returns true if there is a full message available in the buffer, or if we
121 // will have to read more data from disk.
122 bool MessageAvailable();
123
124 // Returns a span with the data for a message from the log file, excluding the
125 // size.
126 absl::Span<const uint8_t> ReadMessage();
127
128 // Queues at least max_out_of_order_duration_ messages into channels_.
129 void QueueMessages();
130
131 // We need to read a large chunk at a time, then kit it up into parts and
132 // sort.
133 //
134 // We want to read 256 KB chunks at a time. This is the fastest read size.
135 // This leaves us with a fragmentation problem though.
136 //
137 // The easy answer is to read 256 KB chunks. Then, malloc and memcpy those
138 // chunks into single flatbuffer messages and manage them in a sorted queue.
139 // Everything is copied three times (into 256 kb buffer, then into separate
140 // buffer, then into sender), but none of it is all that expensive. We can
141 // optimize if it is slow later.
142 //
143 // As we place the elements in the sorted list of times, keep doing this until
144 // we read a message that is newer than the threshold.
145 //
146 // Then repeat. Keep filling up the sorted list with 256 KB chunks (need a
147 // small state machine so we can resume), and keep pulling messages back out
148 // and sending.
149 //
150 // For sorting, we want to use the fact that each channel is sorted, and then
151 // merge sort the channels. Have a vector of deques, and then hold a sorted
152 // list of pointers to those.
153 //
154 // TODO(austin): Multithreaded read at some point. Gotta go faster!
155 // Especially if we start compressing.
156
157 // Allocator which doesn't zero initialize memory.
158 template <typename T>
159 struct DefaultInitAllocator {
160 typedef T value_type;
161
162 template <typename U>
163 void construct(U *p) {
164 ::new (static_cast<void *>(p)) U;
165 }
166
167 template <typename U, typename... Args>
168 void construct(U *p, Args &&... args) {
169 ::new (static_cast<void *>(p)) U(std::forward<Args>(args)...);
170 }
171
172 T *allocate(std::size_t n) {
173 return reinterpret_cast<T *>(::operator new(sizeof(T) * n));
174 }
175
176 template <typename U>
177 void deallocate(U *p, std::size_t /*n*/) {
178 ::operator delete(static_cast<void *>(p));
179 }
180 };
181
182 // Minimum amount of data to queue up for sorting before we are guarenteed to
183 // not see data out of order.
184 std::chrono::nanoseconds max_out_of_order_duration_;
185
186 // File descriptor for the log file.
187 int fd_ = -1;
188
189 EventLoop *event_loop_;
190 TimerHandler *timer_handler_;
191
192 // Vector to read into. This uses an allocator which doesn't zero initialize
193 // the memory.
194 std::vector<uint8_t, DefaultInitAllocator<uint8_t>> data_;
195
196 // Amount of data consumed already in data_.
197 size_t consumed_data_ = 0;
198
199 // Vector holding the data for the configuration.
200 std::vector<uint8_t> configuration_;
201
202 // Moves the message to the correct channel queue.
203 void EmplaceDataBack(FlatbufferVector<MessageHeader> &&new_data);
204
205 // Pushes a pointer to the channel for the given timestamp to the sorted
206 // channel list.
207 void PushChannelHeap(monotonic_clock::time_point timestamp,
208 int channel_index);
209
210 // Returns a pointer to the channel with the oldest message in it, and the
211 // timestamp.
212 const std::pair<monotonic_clock::time_point, int> &oldest_message() const {
213 return channel_heap_.front();
214 }
215
216 // Pops a pointer to the channel with the oldest message in it, and the
217 // timestamp.
218 std::pair<monotonic_clock::time_point, int> PopOldestChannel();
219
220 // Datastructure to hold the list of messages, cached timestamp for the oldest
221 // message, and sender to send with.
222 struct ChannelData {
223 monotonic_clock::time_point oldest_timestamp = monotonic_clock::min_time;
224 std::deque<FlatbufferVector<MessageHeader>> data;
225 std::unique_ptr<RawSender> raw_sender;
226
227 // Returns the oldest message.
228 const FlatbufferVector<MessageHeader> &front() { return data.front(); }
229
230 // Returns the timestamp for the oldest message.
231 const monotonic_clock::time_point front_timestamp() {
232 return monotonic_clock::time_point(
233 std::chrono::nanoseconds(front().message().monotonic_sent_time()));
234 }
235 };
236
237 // List of channels and messages for them.
238 std::vector<ChannelData> channels_;
239
240 // Heap of channels so we can track which channel to send next.
241 std::vector<std::pair<monotonic_clock::time_point, int>> channel_heap_;
242
243 // Timestamp of the newest message in a channel queue.
244 monotonic_clock::time_point newest_timestamp_ = monotonic_clock::min_time;
245
246 // The time at which we need to read another chunk from the logfile.
247 monotonic_clock::time_point queue_data_time_ = monotonic_clock::min_time;
248
249 // Cached bit for if we have reached the end of the file. Otherwise we will
250 // hammer on the kernel asking for more data each time we send.
251 bool end_of_file_ = false;
252};
253
254} // namespace logger
255} // namespace aos
256
257#endif // AOS_EVENTS_LOGGER_H_