blob: 3c75f295b20dfc4dff1cd598e18a3d949f404b76 [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
Brian Smartt03c00da2022-02-24 10:25:00 -0800131 // Restart logging using a new naming scheme. Intended for log rotation.
132 // Returns a unique_ptr to the prior log_namer instance.
133 std::unique_ptr<LogNamer> RestartLogging(std::unique_ptr<LogNamer> log_namer,
134 std::optional<UUID> log_start_uuid = std::nullopt);
135
Austin Schuh6bb8a822021-03-31 23:04:39 -0700136 // Moves the current log location to the new name. Returns true if a change
137 // was made, false otherwise.
138 // Only renaming the folder is supported, not the file base name.
139 bool RenameLogBase(std::string new_base_name);
140
Austin Schuhb06f03b2021-02-17 22:00:37 -0800141 // Stops logging. Ensures any messages through end_time make it into the log.
142 //
143 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
144 //
145 // Returns the LogNamer in case the caller wants to do anything else with it
146 // before destroying it.
147 std::unique_ptr<LogNamer> StopLogging(
148 aos::monotonic_clock::time_point end_time);
149
150 // Returns whether a log is currently being written.
151 bool is_started() const { return static_cast<bool>(log_namer_); }
152
153 // Shortcut to call StartLogging with a LocalLogNamer when event processing
154 // starts.
155 void StartLoggingLocalNamerOnRun(std::string base_name) {
156 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700157 StartLogging(
158 std::make_unique<LocalLogNamer>(base_name, event_loop_, node_));
Austin Schuhb06f03b2021-02-17 22:00:37 -0800159 });
160 }
161
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700162 // Shortcut to call StartLogging with a MultiNodeLogNamer when event
163 // processing starts.
164 void StartLoggingOnRun(std::string base_name) {
165 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700166 StartLogging(std::make_unique<MultiNodeLogNamer>(
167 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700168 });
169 }
170
Austin Schuhb06f03b2021-02-17 22:00:37 -0800171 private:
172 // Structure to track both a fetcher, and if the data fetched has been
173 // written. We may want to delay writing data to disk so that we don't let
174 // data get too far out of order when written to disk so we can avoid making
175 // it too hard to sort when reading.
176 struct FetcherStruct {
177 std::unique_ptr<RawFetcher> fetcher;
178 bool written = false;
179
180 // Channel index to log to.
181 int channel_index = -1;
182 const Channel *channel = nullptr;
183 const Node *timestamp_node = nullptr;
184
185 LogType log_type = LogType::kLogMessage;
186
187 // We fill out the metadata at construction, but the actual writers have to
188 // be updated each time we start logging. To avoid duplicating the complex
189 // logic determining whether each writer should be initialized, we just
190 // stash the answer in separate member variables.
191 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700192 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800193 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700194 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800195 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700196 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800197
198 // Node which this data is from, or -1 if it is unknown.
199 int data_node_index = -1;
200 // Node that this timestamp is for, or -1 if it is known.
201 int timestamp_node_index = -1;
202 // Node that the contents this contents_writer will log are from.
203 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700204
205 // If true, this message is being sent over a reliable channel.
206 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800207
208 // One of the following will be populated. If channel_reliable_contents is
209 // non zero size, it contains a mapping from the event loop channel (not the
210 // logged channel) to a bool telling us if that particular channel is
211 // reliable.
212 //
213 // If channel_reliable_contents is empty, reliable_contents will contain the
214 // same info for all contents logged here. This is the predominant case for
215 // split timestamp channels (the prefered approach).
216 bool reliable_contents = false;
217 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800218 };
219
220 // Vector mapping from the channel index from the event loop to the logged
221 // channel index.
222 std::vector<int> event_loop_to_logged_channel_index_;
223
Brian Smartt03c00da2022-02-24 10:25:00 -0800224 // Start/Restart write configuration into LogNamer space.
225 std::string WriteConfiguration(LogNamer* log_namer);
226
Austin Schuhb06f03b2021-02-17 22:00:37 -0800227 void WriteHeader();
228
Austin Schuh73340842021-07-30 22:32:06 -0700229 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800230 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700231 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800232
Austin Schuhb06f03b2021-02-17 22:00:37 -0800233 bool MaybeUpdateTimestamp(
234 const Node *node, int node_index,
235 aos::monotonic_clock::time_point monotonic_start_time,
236 aos::realtime_clock::time_point realtime_start_time);
237
Austin Schuh30586902021-03-30 22:54:08 -0700238 void DoLogData(const monotonic_clock::time_point end_time,
239 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800240
241 void WriteMissingTimestamps();
242
Brian Smartt03c00da2022-02-24 10:25:00 -0800243 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
244 void WriteTimestamps(NewDataWriter *timestamps_writer, const FetcherStruct &f);
245 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
246
247 void WriteFetchedRecord(FetcherStruct &f);
248
Austin Schuh855f8932021-03-19 22:01:32 -0700249 // Fetches from each channel until all the data is logged. This is dangerous
250 // because it lets you log for more than 1 period. All calls need to verify
251 // that t isn't greater than 1 period in the future.
Brian Smartt03c00da2022-02-24 10:25:00 -0800252 // Returns true if there is at least one message that has been fetched but
253 // not yet written.
254 bool LogUntil(monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800255
256 void RecordFetchResult(aos::monotonic_clock::time_point start,
257 aos::monotonic_clock::time_point end, bool got_new,
258 FetcherStruct *fetcher);
259
260 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
261 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800262 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800263
Austin Schuhb06f03b2021-02-17 22:00:37 -0800264 EventLoop *const event_loop_;
265 // The configuration to place at the top of the log file.
266 const Configuration *const configuration_;
267
Austin Schuh5b728b72021-06-16 14:57:15 -0700268 // The node that is writing the log.
269 // For most cases, this is the same node as the node that is reading the
270 // messages. However, in some cases, these two nodes may be different. i.e. if
271 // one node reading and modifying the messages, and another node is listening
272 // and saving those messages to another log.
273 //
274 // node_ is a pointer to the writing node, and that node is guaranteed to be
275 // in configuration_ which is the configuration being written to the top of
276 // the log file.
277 const Node *const node_;
278 // The node_index_ is the index of the node in configuration_.
279 const size_t node_index_;
280
Austin Schuhb06f03b2021-02-17 22:00:37 -0800281 UUID log_event_uuid_ = UUID::Zero();
282 const UUID logger_instance_uuid_ = UUID::Random();
283 std::unique_ptr<LogNamer> log_namer_;
284 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700285 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800286
287 // Name to save in the log file. Defaults to hostname.
288 std::string name_;
289
290 std::function<void()> on_logged_period_ = []() {};
291
292 std::chrono::nanoseconds max_message_fetch_time_ =
293 std::chrono::nanoseconds::zero();
294 int max_message_fetch_time_channel_ = -1;
295 int max_message_fetch_time_size_ = -1;
296 std::chrono::nanoseconds total_message_fetch_time_ =
297 std::chrono::nanoseconds::zero();
298 int total_message_fetch_count_ = 0;
299 int64_t total_message_fetch_bytes_ = 0;
300
301 std::chrono::nanoseconds total_nop_fetch_time_ =
302 std::chrono::nanoseconds::zero();
303 int total_nop_fetch_count_ = 0;
304
305 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
306 int max_copy_time_channel_ = -1;
307 int max_copy_time_size_ = -1;
308 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
309 int total_copy_count_ = 0;
310 int64_t total_copy_bytes_ = 0;
311
312 std::vector<FetcherStruct> fetchers_;
313 TimerHandler *timer_handler_;
314
315 // Period to poll the channels.
316 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
317
318 // Last time that data was written for all channels to disk.
319 monotonic_clock::time_point last_synchronized_time_;
320
321 // Max size that the header has consumed. This much extra data will be
322 // reserved in the builder to avoid reallocating.
323 size_t max_header_size_ = 0;
324
325 // If true, write the message header into a separate file.
326 bool separate_config_ = true;
327
328 // Fetcher for all the statistics from all the nodes.
329 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800330};
331
332} // namespace logger
333} // namespace aos
334
335#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_