blob: 23ab34909aa061a66a5bc3f9e88f1add612a6058 [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
Austin Schuhfa712682022-05-11 16:43:42 -070046 void set_logger_sha1(std::string_view sha1) { logger_sha1_ = sha1; }
47 void set_logger_version(std::string_view version) {
48 logger_version_ = version;
49 }
50
Austin Schuhb06f03b2021-02-17 22:00:37 -080051 // Sets the callback to run after each period of data is logged. Defaults to
52 // doing nothing.
53 //
54 // This callback may safely do things like call Rotate().
55 void set_on_logged_period(std::function<void()> on_logged_period) {
56 on_logged_period_ = std::move(on_logged_period);
57 }
58
59 void set_separate_config(bool separate_config) {
60 separate_config_ = separate_config;
61 }
62
63 // Sets the period between polling the data. Defaults to 100ms.
64 //
65 // Changing this while a set of files is being written may result in
66 // unreadable files.
67 void set_polling_period(std::chrono::nanoseconds polling_period) {
68 polling_period_ = polling_period;
69 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070070 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080071
Austin Schuh34f9e482021-03-31 22:54:18 -070072 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080073 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
74
75 // The maximum time for a single fetch which returned a message, or 0 if none
76 // of those have happened.
77 std::chrono::nanoseconds max_message_fetch_time() const {
78 return max_message_fetch_time_;
79 }
80 // The channel for that longest fetch which returned a message, or -1 if none
81 // of those have happened.
82 int max_message_fetch_time_channel() const {
83 return max_message_fetch_time_channel_;
84 }
85 // The size of the message returned by that longest fetch, or -1 if none of
86 // those have happened.
87 int max_message_fetch_time_size() const {
88 return max_message_fetch_time_size_;
89 }
90 // The total time spent fetching messages.
91 std::chrono::nanoseconds total_message_fetch_time() const {
92 return total_message_fetch_time_;
93 }
94 // The total number of fetch calls which returned messages.
95 int total_message_fetch_count() const { return total_message_fetch_count_; }
96 // The total number of bytes fetched.
97 int64_t total_message_fetch_bytes() const {
98 return total_message_fetch_bytes_;
99 }
100
101 // The total time spent in fetches which did not return a message.
102 std::chrono::nanoseconds total_nop_fetch_time() const {
103 return total_nop_fetch_time_;
104 }
105 // The total number of fetches which did not return a message.
106 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
107
108 // The maximum time for a single copy, or 0 if none of those have happened.
109 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
110 // The channel for that longest copy, or -1 if none of those have happened.
111 int max_copy_time_channel() const { return max_copy_time_channel_; }
112 // The size of the message for that longest copy, or -1 if none of those have
113 // happened.
114 int max_copy_time_size() const { return max_copy_time_size_; }
115 // The total time spent copying messages.
116 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
117 // The total number of messages copied.
118 int total_copy_count() const { return total_copy_count_; }
119 // The total number of bytes copied.
120 int64_t total_copy_bytes() const { return total_copy_bytes_; }
121
122 void ResetStatisics();
123
124 // Rotates the log file(s), triggering new part files to be written for each
125 // log file.
126 void Rotate();
127
128 // Starts logging to files with the given naming scheme.
129 //
130 // log_start_uuid may be used to tie this log event to other log events across
131 // multiple nodes. The default (empty string) indicates there isn't one
132 // available.
133 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700134 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800135
Brian Smartt03c00da2022-02-24 10:25:00 -0800136 // Restart logging using a new naming scheme. Intended for log rotation.
137 // Returns a unique_ptr to the prior log_namer instance.
138 std::unique_ptr<LogNamer> RestartLogging(std::unique_ptr<LogNamer> log_namer,
139 std::optional<UUID> log_start_uuid = std::nullopt);
140
Austin Schuh6bb8a822021-03-31 23:04:39 -0700141 // Moves the current log location to the new name. Returns true if a change
142 // was made, false otherwise.
143 // Only renaming the folder is supported, not the file base name.
144 bool RenameLogBase(std::string new_base_name);
145
Austin Schuhb06f03b2021-02-17 22:00:37 -0800146 // Stops logging. Ensures any messages through end_time make it into the log.
147 //
148 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
149 //
150 // Returns the LogNamer in case the caller wants to do anything else with it
151 // before destroying it.
152 std::unique_ptr<LogNamer> StopLogging(
153 aos::monotonic_clock::time_point end_time);
154
155 // Returns whether a log is currently being written.
156 bool is_started() const { return static_cast<bool>(log_namer_); }
157
158 // Shortcut to call StartLogging with a LocalLogNamer when event processing
159 // starts.
160 void StartLoggingLocalNamerOnRun(std::string base_name) {
161 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700162 StartLogging(
163 std::make_unique<LocalLogNamer>(base_name, event_loop_, node_));
Austin Schuhb06f03b2021-02-17 22:00:37 -0800164 });
165 }
166
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700167 // Shortcut to call StartLogging with a MultiNodeLogNamer when event
168 // processing starts.
169 void StartLoggingOnRun(std::string base_name) {
170 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700171 StartLogging(std::make_unique<MultiNodeLogNamer>(
172 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700173 });
174 }
175
Austin Schuhb06f03b2021-02-17 22:00:37 -0800176 private:
177 // Structure to track both a fetcher, and if the data fetched has been
178 // written. We may want to delay writing data to disk so that we don't let
179 // data get too far out of order when written to disk so we can avoid making
180 // it too hard to sort when reading.
181 struct FetcherStruct {
182 std::unique_ptr<RawFetcher> fetcher;
183 bool written = false;
184
185 // Channel index to log to.
186 int channel_index = -1;
187 const Channel *channel = nullptr;
188 const Node *timestamp_node = nullptr;
189
190 LogType log_type = LogType::kLogMessage;
191
192 // We fill out the metadata at construction, but the actual writers have to
193 // be updated each time we start logging. To avoid duplicating the complex
194 // logic determining whether each writer should be initialized, we just
195 // stash the answer in separate member variables.
196 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700197 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800198 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700199 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800200 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700201 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800202
203 // Node which this data is from, or -1 if it is unknown.
204 int data_node_index = -1;
205 // Node that this timestamp is for, or -1 if it is known.
206 int timestamp_node_index = -1;
207 // Node that the contents this contents_writer will log are from.
208 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700209
210 // If true, this message is being sent over a reliable channel.
211 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800212
213 // One of the following will be populated. If channel_reliable_contents is
214 // non zero size, it contains a mapping from the event loop channel (not the
215 // logged channel) to a bool telling us if that particular channel is
216 // reliable.
217 //
218 // If channel_reliable_contents is empty, reliable_contents will contain the
219 // same info for all contents logged here. This is the predominant case for
220 // split timestamp channels (the prefered approach).
221 bool reliable_contents = false;
222 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800223 };
224
225 // Vector mapping from the channel index from the event loop to the logged
226 // channel index.
227 std::vector<int> event_loop_to_logged_channel_index_;
228
Brian Smartt03c00da2022-02-24 10:25:00 -0800229 // Start/Restart write configuration into LogNamer space.
230 std::string WriteConfiguration(LogNamer* log_namer);
231
Austin Schuh41f8df92022-04-15 11:45:52 -0700232 void WriteHeader(aos::monotonic_clock::time_point monotonic_start_time =
233 aos::monotonic_clock::min_time,
234 aos::realtime_clock::time_point realtime_start_time =
235 aos::realtime_clock::min_time);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800236
Austin Schuh73340842021-07-30 22:32:06 -0700237 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800238 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700239 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800240
Austin Schuhb06f03b2021-02-17 22:00:37 -0800241 bool MaybeUpdateTimestamp(
242 const Node *node, int node_index,
243 aos::monotonic_clock::time_point monotonic_start_time,
244 aos::realtime_clock::time_point realtime_start_time);
245
Austin Schuh30586902021-03-30 22:54:08 -0700246 void DoLogData(const monotonic_clock::time_point end_time,
247 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800248
249 void WriteMissingTimestamps();
250
Brian Smartt03c00da2022-02-24 10:25:00 -0800251 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
252 void WriteTimestamps(NewDataWriter *timestamps_writer, const FetcherStruct &f);
253 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
254
255 void WriteFetchedRecord(FetcherStruct &f);
256
Austin Schuh855f8932021-03-19 22:01:32 -0700257 // Fetches from each channel until all the data is logged. This is dangerous
258 // because it lets you log for more than 1 period. All calls need to verify
259 // that t isn't greater than 1 period in the future.
Brian Smartt03c00da2022-02-24 10:25:00 -0800260 // Returns true if there is at least one message that has been fetched but
261 // not yet written.
262 bool LogUntil(monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800263
264 void RecordFetchResult(aos::monotonic_clock::time_point start,
265 aos::monotonic_clock::time_point end, bool got_new,
266 FetcherStruct *fetcher);
267
268 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
269 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800270 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800271
Austin Schuhb06f03b2021-02-17 22:00:37 -0800272 EventLoop *const event_loop_;
273 // The configuration to place at the top of the log file.
274 const Configuration *const configuration_;
275
Austin Schuh5b728b72021-06-16 14:57:15 -0700276 // The node that is writing the log.
277 // For most cases, this is the same node as the node that is reading the
278 // messages. However, in some cases, these two nodes may be different. i.e. if
279 // one node reading and modifying the messages, and another node is listening
280 // and saving those messages to another log.
281 //
282 // node_ is a pointer to the writing node, and that node is guaranteed to be
283 // in configuration_ which is the configuration being written to the top of
284 // the log file.
285 const Node *const node_;
286 // The node_index_ is the index of the node in configuration_.
287 const size_t node_index_;
288
Austin Schuhb06f03b2021-02-17 22:00:37 -0800289 UUID log_event_uuid_ = UUID::Zero();
290 const UUID logger_instance_uuid_ = UUID::Random();
291 std::unique_ptr<LogNamer> log_namer_;
292 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700293 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800294
295 // Name to save in the log file. Defaults to hostname.
296 std::string name_;
Austin Schuhfa712682022-05-11 16:43:42 -0700297 std::string logger_sha1_;
298 std::string logger_version_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800299
300 std::function<void()> on_logged_period_ = []() {};
301
302 std::chrono::nanoseconds max_message_fetch_time_ =
303 std::chrono::nanoseconds::zero();
304 int max_message_fetch_time_channel_ = -1;
305 int max_message_fetch_time_size_ = -1;
306 std::chrono::nanoseconds total_message_fetch_time_ =
307 std::chrono::nanoseconds::zero();
308 int total_message_fetch_count_ = 0;
309 int64_t total_message_fetch_bytes_ = 0;
310
311 std::chrono::nanoseconds total_nop_fetch_time_ =
312 std::chrono::nanoseconds::zero();
313 int total_nop_fetch_count_ = 0;
314
315 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
316 int max_copy_time_channel_ = -1;
317 int max_copy_time_size_ = -1;
318 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
319 int total_copy_count_ = 0;
320 int64_t total_copy_bytes_ = 0;
321
322 std::vector<FetcherStruct> fetchers_;
323 TimerHandler *timer_handler_;
324
325 // Period to poll the channels.
326 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
327
328 // Last time that data was written for all channels to disk.
329 monotonic_clock::time_point last_synchronized_time_;
330
331 // Max size that the header has consumed. This much extra data will be
332 // reserved in the builder to avoid reallocating.
333 size_t max_header_size_ = 0;
334
335 // If true, write the message header into a separate file.
336 bool separate_config_ = true;
337
338 // Fetcher for all the statistics from all the nodes.
339 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800340};
341
342} // namespace logger
343} // namespace aos
344
345#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_