blob: 3d975a306900faf7e3e9888c0c6c45bd91437723 [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]() {
152 StartLogging(
153 std::make_unique<LocalLogNamer>(base_name, event_loop_->node()));
154 });
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]() {
161 StartLogging(std::make_unique<MultiNodeLogNamer>(
162 base_name, event_loop_->configuration(), event_loop_->node()));
163 });
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;
199 };
200
201 // Vector mapping from the channel index from the event loop to the logged
202 // channel index.
203 std::vector<int> event_loop_to_logged_channel_index_;
204
205 struct NodeState {
206 aos::monotonic_clock::time_point monotonic_start_time =
207 aos::monotonic_clock::min_time;
208 aos::realtime_clock::time_point realtime_start_time =
209 aos::realtime_clock::min_time;
210
211 bool has_source_node_boot_uuid = false;
212
213 // This is an initial UUID that is a valid UUID4 and is pretty obvious that
214 // it isn't valid.
Austin Schuhcdd90272021-03-15 12:46:16 -0700215 UUID source_node_boot_uuid = UUID::Zero();
Austin Schuhb06f03b2021-02-17 22:00:37 -0800216
217 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
218 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
219
220 // True if a header has been written to the start of a log file.
221 bool header_written = false;
222 // True if the current written header represents the contents which will
223 // follow. This is cleared when boot_uuid is known to not match anymore.
224 bool header_valid = false;
225
Austin Schuhcdd90272021-03-15 12:46:16 -0700226 // Sets the source_node_boot_uuid, properly updating everything. Returns
227 // true if it changed, false otherwise.
228 bool SetBootUUID(const UUID &new_source_node_boot_uuid) {
229 if (has_source_node_boot_uuid &&
230 source_node_boot_uuid == new_source_node_boot_uuid) {
231 return false;
232 }
Austin Schuhb06f03b2021-02-17 22:00:37 -0800233 source_node_boot_uuid = new_source_node_boot_uuid;
234 header_valid = false;
235 has_source_node_boot_uuid = true;
236
237 flatbuffers::String *source_node_boot_uuid_string =
238 log_file_header.mutable_message()->mutable_source_node_boot_uuid();
Austin Schuhcdd90272021-03-15 12:46:16 -0700239 CHECK_EQ(UUID::kStringSize, source_node_boot_uuid_string->size());
240 source_node_boot_uuid.CopyTo(source_node_boot_uuid_string->data());
241
242 return true;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800243 }
244 };
245
246 void WriteHeader();
247
248 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
249 const Node *node, std::string_view config_sha256);
250
251 // Writes the header for the provided node if enough information is valid.
252 void MaybeWriteHeader(int node_index);
253 // Overload for when we already know node as well.
254 void MaybeWriteHeader(int node_index, const Node *node);
255
256 bool MaybeUpdateTimestamp(
257 const Node *node, int node_index,
258 aos::monotonic_clock::time_point monotonic_start_time,
259 aos::realtime_clock::time_point realtime_start_time);
260
Austin Schuh30586902021-03-30 22:54:08 -0700261 void DoLogData(const monotonic_clock::time_point end_time,
262 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800263
264 void WriteMissingTimestamps();
265
Austin Schuh855f8932021-03-19 22:01:32 -0700266 // Fetches from each channel until all the data is logged. This is dangerous
267 // because it lets you log for more than 1 period. All calls need to verify
268 // that t isn't greater than 1 period in the future.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800269 void LogUntil(monotonic_clock::time_point t);
270
271 void RecordFetchResult(aos::monotonic_clock::time_point start,
272 aos::monotonic_clock::time_point end, bool got_new,
273 FetcherStruct *fetcher);
274
275 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
276 aos::monotonic_clock::time_point end,
277 FetcherStruct *fetcher);
278
279 // Sets the start time for a specific node.
280 void SetStartTime(
281 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
282 aos::realtime_clock::time_point realtime_start_time,
283 aos::monotonic_clock::time_point logger_monotonic_start_time,
284 aos::realtime_clock::time_point logger_realtime_start_time);
285
286 EventLoop *const event_loop_;
287 // The configuration to place at the top of the log file.
288 const Configuration *const configuration_;
289
290 UUID log_event_uuid_ = UUID::Zero();
291 const UUID logger_instance_uuid_ = UUID::Random();
292 std::unique_ptr<LogNamer> log_namer_;
293 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700294 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800295
296 // Name to save in the log file. Defaults to hostname.
297 std::string name_;
298
299 std::function<void()> on_logged_period_ = []() {};
300
301 std::chrono::nanoseconds max_message_fetch_time_ =
302 std::chrono::nanoseconds::zero();
303 int max_message_fetch_time_channel_ = -1;
304 int max_message_fetch_time_size_ = -1;
305 std::chrono::nanoseconds total_message_fetch_time_ =
306 std::chrono::nanoseconds::zero();
307 int total_message_fetch_count_ = 0;
308 int64_t total_message_fetch_bytes_ = 0;
309
310 std::chrono::nanoseconds total_nop_fetch_time_ =
311 std::chrono::nanoseconds::zero();
312 int total_nop_fetch_count_ = 0;
313
314 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
315 int max_copy_time_channel_ = -1;
316 int max_copy_time_size_ = -1;
317 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
318 int total_copy_count_ = 0;
319 int64_t total_copy_bytes_ = 0;
320
321 std::vector<FetcherStruct> fetchers_;
322 TimerHandler *timer_handler_;
323
324 // Period to poll the channels.
325 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
326
327 // Last time that data was written for all channels to disk.
328 monotonic_clock::time_point last_synchronized_time_;
329
330 // Max size that the header has consumed. This much extra data will be
331 // reserved in the builder to avoid reallocating.
332 size_t max_header_size_ = 0;
333
334 // If true, write the message header into a separate file.
335 bool separate_config_ = true;
336
337 // Fetcher for all the statistics from all the nodes.
338 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
339
340 std::vector<NodeState> node_state_;
341};
342
343} // namespace logger
344} // namespace aos
345
346#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_