blob: c546286b0b9527d9acd56627fc0e5e229791853e [file] [log] [blame]
Austin Schuhb06f03b2021-02-17 22:00:37 -08001#ifndef AOS_EVENTS_LOGGING_LOG_WRITER_H_
2#define AOS_EVENTS_LOGGING_LOG_WRITER_H_
3
4#include <chrono>
5#include <string_view>
6#include <vector>
7
8#include "aos/events/event_loop.h"
9#include "aos/events/logging/log_namer.h"
10#include "aos/events/logging/logfile_utils.h"
11#include "aos/events/logging/logger_generated.h"
Austin Schuhb06f03b2021-02-17 22:00:37 -080012#include "aos/events/simulated_event_loop.h"
13#include "aos/network/message_bridge_server_generated.h"
14#include "aos/network/remote_message_generated.h"
15#include "aos/time/time.h"
Austin Schuh4385b142021-03-14 21:31:13 -070016#include "aos/uuid.h"
Austin Schuhb06f03b2021-02-17 22:00:37 -080017#include "flatbuffers/flatbuffers.h"
18
19namespace aos {
20namespace logger {
21
22// Logs all channels available in the event loop to disk every 100 ms.
23// Start by logging one message per channel to capture any state and
24// configuration that is sent rately on a channel and would affect execution.
25class Logger {
26 public:
27 // Constructs a logger.
28 // event_loop: The event loop used to read the messages.
29 // configuration: When provided, this is the configuration to log, and the
30 // configuration to use for the channel list to log. If not provided,
31 // this becomes the configuration from the event loop.
32 // should_log: When provided, a filter for channels to log. If not provided,
33 // all available channels are logged.
34 Logger(EventLoop *event_loop)
35 : Logger(event_loop, event_loop->configuration()) {}
36 Logger(EventLoop *event_loop, const Configuration *configuration)
37 : Logger(event_loop, configuration,
38 [](const Channel *) { return true; }) {}
39 Logger(EventLoop *event_loop, const Configuration *configuration,
40 std::function<bool(const Channel *)> should_log);
41 ~Logger();
42
43 // Overrides the name in the log file header.
44 void set_name(std::string_view name) { name_ = name; }
45
46 // Sets the callback to run after each period of data is logged. Defaults to
47 // doing nothing.
48 //
49 // This callback may safely do things like call Rotate().
50 void set_on_logged_period(std::function<void()> on_logged_period) {
51 on_logged_period_ = std::move(on_logged_period);
52 }
53
54 void set_separate_config(bool separate_config) {
55 separate_config_ = separate_config;
56 }
57
58 // Sets the period between polling the data. Defaults to 100ms.
59 //
60 // Changing this while a set of files is being written may result in
61 // unreadable files.
62 void set_polling_period(std::chrono::nanoseconds polling_period) {
63 polling_period_ = polling_period;
64 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070065 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080066
Austin Schuh34f9e482021-03-31 22:54:18 -070067 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080068 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
69
70 // The maximum time for a single fetch which returned a message, or 0 if none
71 // of those have happened.
72 std::chrono::nanoseconds max_message_fetch_time() const {
73 return max_message_fetch_time_;
74 }
75 // The channel for that longest fetch which returned a message, or -1 if none
76 // of those have happened.
77 int max_message_fetch_time_channel() const {
78 return max_message_fetch_time_channel_;
79 }
80 // The size of the message returned by that longest fetch, or -1 if none of
81 // those have happened.
82 int max_message_fetch_time_size() const {
83 return max_message_fetch_time_size_;
84 }
85 // The total time spent fetching messages.
86 std::chrono::nanoseconds total_message_fetch_time() const {
87 return total_message_fetch_time_;
88 }
89 // The total number of fetch calls which returned messages.
90 int total_message_fetch_count() const { return total_message_fetch_count_; }
91 // The total number of bytes fetched.
92 int64_t total_message_fetch_bytes() const {
93 return total_message_fetch_bytes_;
94 }
95
96 // The total time spent in fetches which did not return a message.
97 std::chrono::nanoseconds total_nop_fetch_time() const {
98 return total_nop_fetch_time_;
99 }
100 // The total number of fetches which did not return a message.
101 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
102
103 // The maximum time for a single copy, or 0 if none of those have happened.
104 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
105 // The channel for that longest copy, or -1 if none of those have happened.
106 int max_copy_time_channel() const { return max_copy_time_channel_; }
107 // The size of the message for that longest copy, or -1 if none of those have
108 // happened.
109 int max_copy_time_size() const { return max_copy_time_size_; }
110 // The total time spent copying messages.
111 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
112 // The total number of messages copied.
113 int total_copy_count() const { return total_copy_count_; }
114 // The total number of bytes copied.
115 int64_t total_copy_bytes() const { return total_copy_bytes_; }
116
117 void ResetStatisics();
118
119 // Rotates the log file(s), triggering new part files to be written for each
120 // log file.
121 void Rotate();
122
123 // Starts logging to files with the given naming scheme.
124 //
125 // log_start_uuid may be used to tie this log event to other log events across
126 // multiple nodes. The default (empty string) indicates there isn't one
127 // available.
128 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700129 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800130
131 // Stops logging. Ensures any messages through end_time make it into the log.
132 //
133 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
134 //
135 // Returns the LogNamer in case the caller wants to do anything else with it
136 // before destroying it.
137 std::unique_ptr<LogNamer> StopLogging(
138 aos::monotonic_clock::time_point end_time);
139
140 // Returns whether a log is currently being written.
141 bool is_started() const { return static_cast<bool>(log_namer_); }
142
143 // Shortcut to call StartLogging with a LocalLogNamer when event processing
144 // starts.
145 void StartLoggingLocalNamerOnRun(std::string base_name) {
146 event_loop_->OnRun([this, base_name]() {
147 StartLogging(
148 std::make_unique<LocalLogNamer>(base_name, event_loop_->node()));
149 });
150 }
151
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700152 // Shortcut to call StartLogging with a MultiNodeLogNamer when event
153 // processing starts.
154 void StartLoggingOnRun(std::string base_name) {
155 event_loop_->OnRun([this, base_name]() {
156 StartLogging(std::make_unique<MultiNodeLogNamer>(
157 base_name, event_loop_->configuration(), event_loop_->node()));
158 });
159 }
160
Austin Schuhb06f03b2021-02-17 22:00:37 -0800161 private:
162 // Structure to track both a fetcher, and if the data fetched has been
163 // written. We may want to delay writing data to disk so that we don't let
164 // data get too far out of order when written to disk so we can avoid making
165 // it too hard to sort when reading.
166 struct FetcherStruct {
167 std::unique_ptr<RawFetcher> fetcher;
168 bool written = false;
169
170 // Channel index to log to.
171 int channel_index = -1;
172 const Channel *channel = nullptr;
173 const Node *timestamp_node = nullptr;
174
175 LogType log_type = LogType::kLogMessage;
176
177 // We fill out the metadata at construction, but the actual writers have to
178 // be updated each time we start logging. To avoid duplicating the complex
179 // logic determining whether each writer should be initialized, we just
180 // stash the answer in separate member variables.
181 bool wants_writer = false;
182 DetachedBufferWriter *writer = nullptr;
183 bool wants_timestamp_writer = false;
184 DetachedBufferWriter *timestamp_writer = nullptr;
185 bool wants_contents_writer = false;
186 DetachedBufferWriter *contents_writer = nullptr;
187
188 // Node which this data is from, or -1 if it is unknown.
189 int data_node_index = -1;
190 // Node that this timestamp is for, or -1 if it is known.
191 int timestamp_node_index = -1;
192 // Node that the contents this contents_writer will log are from.
193 int contents_node_index = -1;
194 };
195
196 // Vector mapping from the channel index from the event loop to the logged
197 // channel index.
198 std::vector<int> event_loop_to_logged_channel_index_;
199
200 struct NodeState {
201 aos::monotonic_clock::time_point monotonic_start_time =
202 aos::monotonic_clock::min_time;
203 aos::realtime_clock::time_point realtime_start_time =
204 aos::realtime_clock::min_time;
205
206 bool has_source_node_boot_uuid = false;
207
208 // This is an initial UUID that is a valid UUID4 and is pretty obvious that
209 // it isn't valid.
Austin Schuhcdd90272021-03-15 12:46:16 -0700210 UUID source_node_boot_uuid = UUID::Zero();
Austin Schuhb06f03b2021-02-17 22:00:37 -0800211
212 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
213 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
214
215 // True if a header has been written to the start of a log file.
216 bool header_written = false;
217 // True if the current written header represents the contents which will
218 // follow. This is cleared when boot_uuid is known to not match anymore.
219 bool header_valid = false;
220
Austin Schuhcdd90272021-03-15 12:46:16 -0700221 // Sets the source_node_boot_uuid, properly updating everything. Returns
222 // true if it changed, false otherwise.
223 bool SetBootUUID(const UUID &new_source_node_boot_uuid) {
224 if (has_source_node_boot_uuid &&
225 source_node_boot_uuid == new_source_node_boot_uuid) {
226 return false;
227 }
Austin Schuhb06f03b2021-02-17 22:00:37 -0800228 source_node_boot_uuid = new_source_node_boot_uuid;
229 header_valid = false;
230 has_source_node_boot_uuid = true;
231
232 flatbuffers::String *source_node_boot_uuid_string =
233 log_file_header.mutable_message()->mutable_source_node_boot_uuid();
Austin Schuhcdd90272021-03-15 12:46:16 -0700234 CHECK_EQ(UUID::kStringSize, source_node_boot_uuid_string->size());
235 source_node_boot_uuid.CopyTo(source_node_boot_uuid_string->data());
236
237 return true;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800238 }
239 };
240
241 void WriteHeader();
242
243 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
244 const Node *node, std::string_view config_sha256);
245
246 // Writes the header for the provided node if enough information is valid.
247 void MaybeWriteHeader(int node_index);
248 // Overload for when we already know node as well.
249 void MaybeWriteHeader(int node_index, const Node *node);
250
251 bool MaybeUpdateTimestamp(
252 const Node *node, int node_index,
253 aos::monotonic_clock::time_point monotonic_start_time,
254 aos::realtime_clock::time_point realtime_start_time);
255
256 void DoLogData(const monotonic_clock::time_point end_time);
257
258 void WriteMissingTimestamps();
259
Austin Schuh855f8932021-03-19 22:01:32 -0700260 // Fetches from each channel until all the data is logged. This is dangerous
261 // because it lets you log for more than 1 period. All calls need to verify
262 // that t isn't greater than 1 period in the future.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800263 void LogUntil(monotonic_clock::time_point t);
264
265 void RecordFetchResult(aos::monotonic_clock::time_point start,
266 aos::monotonic_clock::time_point end, bool got_new,
267 FetcherStruct *fetcher);
268
269 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
270 aos::monotonic_clock::time_point end,
271 FetcherStruct *fetcher);
272
273 // Sets the start time for a specific node.
274 void SetStartTime(
275 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
276 aos::realtime_clock::time_point realtime_start_time,
277 aos::monotonic_clock::time_point logger_monotonic_start_time,
278 aos::realtime_clock::time_point logger_realtime_start_time);
279
280 EventLoop *const event_loop_;
281 // The configuration to place at the top of the log file.
282 const Configuration *const configuration_;
283
284 UUID log_event_uuid_ = UUID::Zero();
285 const UUID logger_instance_uuid_ = UUID::Random();
286 std::unique_ptr<LogNamer> log_namer_;
287 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700288 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800289
290 // Name to save in the log file. Defaults to hostname.
291 std::string name_;
292
293 std::function<void()> on_logged_period_ = []() {};
294
295 std::chrono::nanoseconds max_message_fetch_time_ =
296 std::chrono::nanoseconds::zero();
297 int max_message_fetch_time_channel_ = -1;
298 int max_message_fetch_time_size_ = -1;
299 std::chrono::nanoseconds total_message_fetch_time_ =
300 std::chrono::nanoseconds::zero();
301 int total_message_fetch_count_ = 0;
302 int64_t total_message_fetch_bytes_ = 0;
303
304 std::chrono::nanoseconds total_nop_fetch_time_ =
305 std::chrono::nanoseconds::zero();
306 int total_nop_fetch_count_ = 0;
307
308 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
309 int max_copy_time_channel_ = -1;
310 int max_copy_time_size_ = -1;
311 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
312 int total_copy_count_ = 0;
313 int64_t total_copy_bytes_ = 0;
314
315 std::vector<FetcherStruct> fetchers_;
316 TimerHandler *timer_handler_;
317
318 // Period to poll the channels.
319 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
320
321 // Last time that data was written for all channels to disk.
322 monotonic_clock::time_point last_synchronized_time_;
323
324 // Max size that the header has consumed. This much extra data will be
325 // reserved in the builder to avoid reallocating.
326 size_t max_header_size_ = 0;
327
328 // If true, write the message header into a separate file.
329 bool separate_config_ = true;
330
331 // Fetcher for all the statistics from all the nodes.
332 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
333
334 std::vector<NodeState> node_state_;
335};
336
337} // namespace logger
338} // namespace aos
339
340#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_