blob: 5c8b0c73415ba75bd5e0f49c05165584fbf50e6b [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
Austin Schuh6bb8a822021-03-31 23:04:39 -0700131 // Moves the current log location to the new name. Returns true if a change
132 // was made, false otherwise.
133 // Only renaming the folder is supported, not the file base name.
134 bool RenameLogBase(std::string new_base_name);
135
Austin Schuhb06f03b2021-02-17 22:00:37 -0800136 // Stops logging. Ensures any messages through end_time make it into the log.
137 //
138 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
139 //
140 // Returns the LogNamer in case the caller wants to do anything else with it
141 // before destroying it.
142 std::unique_ptr<LogNamer> StopLogging(
143 aos::monotonic_clock::time_point end_time);
144
145 // Returns whether a log is currently being written.
146 bool is_started() const { return static_cast<bool>(log_namer_); }
147
148 // Shortcut to call StartLogging with a LocalLogNamer when event processing
149 // starts.
150 void StartLoggingLocalNamerOnRun(std::string base_name) {
151 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700152 StartLogging(
153 std::make_unique<LocalLogNamer>(base_name, event_loop_, node_));
Austin Schuhb06f03b2021-02-17 22:00:37 -0800154 });
155 }
156
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700157 // Shortcut to call StartLogging with a MultiNodeLogNamer when event
158 // processing starts.
159 void StartLoggingOnRun(std::string base_name) {
160 event_loop_->OnRun([this, base_name]() {
Austin Schuh5b728b72021-06-16 14:57:15 -0700161 StartLogging(std::make_unique<MultiNodeLogNamer>(
162 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700163 });
164 }
165
Austin Schuhb06f03b2021-02-17 22:00:37 -0800166 private:
167 // Structure to track both a fetcher, and if the data fetched has been
168 // written. We may want to delay writing data to disk so that we don't let
169 // data get too far out of order when written to disk so we can avoid making
170 // it too hard to sort when reading.
171 struct FetcherStruct {
172 std::unique_ptr<RawFetcher> fetcher;
173 bool written = false;
174
175 // Channel index to log to.
176 int channel_index = -1;
177 const Channel *channel = nullptr;
178 const Node *timestamp_node = nullptr;
179
180 LogType log_type = LogType::kLogMessage;
181
182 // We fill out the metadata at construction, but the actual writers have to
183 // be updated each time we start logging. To avoid duplicating the complex
184 // logic determining whether each writer should be initialized, we just
185 // stash the answer in separate member variables.
186 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700187 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800188 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700189 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800190 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700191 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800192
193 // Node which this data is from, or -1 if it is unknown.
194 int data_node_index = -1;
195 // Node that this timestamp is for, or -1 if it is known.
196 int timestamp_node_index = -1;
197 // Node that the contents this contents_writer will log are from.
198 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700199
200 // If true, this message is being sent over a reliable channel.
201 bool reliable_forwarding = false;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800202 };
203
204 // Vector mapping from the channel index from the event loop to the logged
205 // channel index.
206 std::vector<int> event_loop_to_logged_channel_index_;
207
Austin Schuhb06f03b2021-02-17 22:00:37 -0800208 void WriteHeader();
209
Austin Schuh73340842021-07-30 22:32:06 -0700210 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800211 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700212 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800213
Austin Schuhb06f03b2021-02-17 22:00:37 -0800214 bool MaybeUpdateTimestamp(
215 const Node *node, int node_index,
216 aos::monotonic_clock::time_point monotonic_start_time,
217 aos::realtime_clock::time_point realtime_start_time);
218
Austin Schuh30586902021-03-30 22:54:08 -0700219 void DoLogData(const monotonic_clock::time_point end_time,
220 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800221
222 void WriteMissingTimestamps();
223
Austin Schuh855f8932021-03-19 22:01:32 -0700224 // Fetches from each channel until all the data is logged. This is dangerous
225 // because it lets you log for more than 1 period. All calls need to verify
226 // that t isn't greater than 1 period in the future.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800227 void LogUntil(monotonic_clock::time_point t);
228
229 void RecordFetchResult(aos::monotonic_clock::time_point start,
230 aos::monotonic_clock::time_point end, bool got_new,
231 FetcherStruct *fetcher);
232
233 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
234 aos::monotonic_clock::time_point end,
235 FetcherStruct *fetcher);
236
Austin Schuhb06f03b2021-02-17 22:00:37 -0800237 EventLoop *const event_loop_;
238 // The configuration to place at the top of the log file.
239 const Configuration *const configuration_;
240
Austin Schuh5b728b72021-06-16 14:57:15 -0700241 // The node that is writing the log.
242 // For most cases, this is the same node as the node that is reading the
243 // messages. However, in some cases, these two nodes may be different. i.e. if
244 // one node reading and modifying the messages, and another node is listening
245 // and saving those messages to another log.
246 //
247 // node_ is a pointer to the writing node, and that node is guaranteed to be
248 // in configuration_ which is the configuration being written to the top of
249 // the log file.
250 const Node *const node_;
251 // The node_index_ is the index of the node in configuration_.
252 const size_t node_index_;
253
Austin Schuhb06f03b2021-02-17 22:00:37 -0800254 UUID log_event_uuid_ = UUID::Zero();
255 const UUID logger_instance_uuid_ = UUID::Random();
256 std::unique_ptr<LogNamer> log_namer_;
257 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700258 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800259
260 // Name to save in the log file. Defaults to hostname.
261 std::string name_;
262
263 std::function<void()> on_logged_period_ = []() {};
264
265 std::chrono::nanoseconds max_message_fetch_time_ =
266 std::chrono::nanoseconds::zero();
267 int max_message_fetch_time_channel_ = -1;
268 int max_message_fetch_time_size_ = -1;
269 std::chrono::nanoseconds total_message_fetch_time_ =
270 std::chrono::nanoseconds::zero();
271 int total_message_fetch_count_ = 0;
272 int64_t total_message_fetch_bytes_ = 0;
273
274 std::chrono::nanoseconds total_nop_fetch_time_ =
275 std::chrono::nanoseconds::zero();
276 int total_nop_fetch_count_ = 0;
277
278 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
279 int max_copy_time_channel_ = -1;
280 int max_copy_time_size_ = -1;
281 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
282 int total_copy_count_ = 0;
283 int64_t total_copy_bytes_ = 0;
284
285 std::vector<FetcherStruct> fetchers_;
286 TimerHandler *timer_handler_;
287
288 // Period to poll the channels.
289 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
290
291 // Last time that data was written for all channels to disk.
292 monotonic_clock::time_point last_synchronized_time_;
293
294 // Max size that the header has consumed. This much extra data will be
295 // reserved in the builder to avoid reallocating.
296 size_t max_header_size_ = 0;
297
298 // If true, write the message header into a separate file.
299 bool separate_config_ = true;
300
301 // Fetcher for all the statistics from all the nodes.
302 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800303};
304
305} // namespace logger
306} // namespace aos
307
308#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_