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