blob: eb69d7e3c61af5058b887d1fe3ee4231c751c7dd [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
Philipp Schrader790cb542023-07-05 21:06:52 -07008#include "flatbuffers/flatbuffers.h"
9
Austin Schuhb06f03b2021-02-17 22:00:37 -080010#include "aos/events/event_loop.h"
11#include "aos/events/logging/log_namer.h"
12#include "aos/events/logging/logfile_utils.h"
13#include "aos/events/logging/logger_generated.h"
Austin Schuhb06f03b2021-02-17 22:00:37 -080014#include "aos/events/simulated_event_loop.h"
15#include "aos/network/message_bridge_server_generated.h"
16#include "aos/network/remote_message_generated.h"
17#include "aos/time/time.h"
Austin Schuh4385b142021-03-14 21:31:13 -070018#include "aos/uuid.h"
Austin Schuhb06f03b2021-02-17 22:00:37 -080019
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -080020namespace aos::logger {
Austin Schuhb06f03b2021-02-17 22:00:37 -080021
Austin Schuh3b2b5b52023-07-05 11:36:46 -070022// Packs the provided configuration into the separate config LogFileHeader
23// container.
24aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> PackConfiguration(
25 const Configuration *const configuration);
26
Austin Schuhb06f03b2021-02-17 22:00:37 -080027// Logs all channels available in the event loop to disk every 100 ms.
28// Start by logging one message per channel to capture any state and
29// configuration that is sent rately on a channel and would affect execution.
30class Logger {
31 public:
32 // Constructs a logger.
33 // event_loop: The event loop used to read the messages.
34 // configuration: When provided, this is the configuration to log, and the
35 // configuration to use for the channel list to log. If not provided,
36 // this becomes the configuration from the event loop.
37 // should_log: When provided, a filter for channels to log. If not provided,
38 // all available channels are logged.
39 Logger(EventLoop *event_loop)
40 : Logger(event_loop, event_loop->configuration()) {}
41 Logger(EventLoop *event_loop, const Configuration *configuration)
42 : Logger(event_loop, configuration,
43 [](const Channel *) { return true; }) {}
44 Logger(EventLoop *event_loop, const Configuration *configuration,
45 std::function<bool(const Channel *)> should_log);
46 ~Logger();
47
48 // Overrides the name in the log file header.
49 void set_name(std::string_view name) { name_ = name; }
50
Austin Schuhfa712682022-05-11 16:43:42 -070051 void set_logger_sha1(std::string_view sha1) { logger_sha1_ = sha1; }
52 void set_logger_version(std::string_view version) {
53 logger_version_ = version;
54 }
55
Austin Schuh2f864452023-07-17 14:53:08 -070056 // Sets the callback to run *after* each period of data is logged. Defaults
57 // to doing nothing. The argument to the callback is the time which we just
58 // wrote until. This is not called when rotating or finishing logs.
Austin Schuhb06f03b2021-02-17 22:00:37 -080059 //
60 // This callback may safely do things like call Rotate().
Austin Schuh2f864452023-07-17 14:53:08 -070061 void set_on_logged_period(
62 std::function<void(aos::monotonic_clock::time_point t)>
63 on_logged_period) {
Austin Schuhb06f03b2021-02-17 22:00:37 -080064 on_logged_period_ = std::move(on_logged_period);
65 }
66
67 void set_separate_config(bool separate_config) {
68 separate_config_ = separate_config;
69 }
70
Austin Schuh2d612c82023-07-17 13:37:48 -070071 // Sets the amount to run the logger behind the current time. This lets us
72 // make decisions about rotating or stopping logging before something happens.
73 // Using this to start logging in the past isn't yet supported. This can be
74 // changed at runtime, but will only influence future writes, not what is
75 // already written.
76 void set_logging_delay(std::chrono::nanoseconds logging_delay) {
77 logging_delay_ = logging_delay;
78 }
Philipp Schrader78dc1212023-08-16 18:17:47 -070079 // Returns the current logging delay.
80 std::chrono::nanoseconds logging_delay() const { return logging_delay_; }
Austin Schuh2d612c82023-07-17 13:37:48 -070081
Austin Schuhb06f03b2021-02-17 22:00:37 -080082 // Sets the period between polling the data. Defaults to 100ms.
83 //
84 // Changing this while a set of files is being written may result in
85 // unreadable files.
86 void set_polling_period(std::chrono::nanoseconds polling_period) {
87 polling_period_ = polling_period;
88 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070089 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080090
Austin Schuh34f9e482021-03-31 22:54:18 -070091 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080092 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
93
94 // The maximum time for a single fetch which returned a message, or 0 if none
95 // of those have happened.
96 std::chrono::nanoseconds max_message_fetch_time() const {
97 return max_message_fetch_time_;
98 }
99 // The channel for that longest fetch which returned a message, or -1 if none
100 // of those have happened.
101 int max_message_fetch_time_channel() const {
102 return max_message_fetch_time_channel_;
103 }
104 // The size of the message returned by that longest fetch, or -1 if none of
105 // those have happened.
106 int max_message_fetch_time_size() const {
107 return max_message_fetch_time_size_;
108 }
109 // The total time spent fetching messages.
110 std::chrono::nanoseconds total_message_fetch_time() const {
111 return total_message_fetch_time_;
112 }
113 // The total number of fetch calls which returned messages.
114 int total_message_fetch_count() const { return total_message_fetch_count_; }
115 // The total number of bytes fetched.
116 int64_t total_message_fetch_bytes() const {
117 return total_message_fetch_bytes_;
118 }
119
120 // The total time spent in fetches which did not return a message.
121 std::chrono::nanoseconds total_nop_fetch_time() const {
122 return total_nop_fetch_time_;
123 }
124 // The total number of fetches which did not return a message.
125 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
126
127 // The maximum time for a single copy, or 0 if none of those have happened.
128 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
129 // The channel for that longest copy, or -1 if none of those have happened.
130 int max_copy_time_channel() const { return max_copy_time_channel_; }
131 // The size of the message for that longest copy, or -1 if none of those have
132 // happened.
133 int max_copy_time_size() const { return max_copy_time_size_; }
134 // The total time spent copying messages.
135 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
136 // The total number of messages copied.
137 int total_copy_count() const { return total_copy_count_; }
138 // The total number of bytes copied.
139 int64_t total_copy_bytes() const { return total_copy_bytes_; }
140
Philipp Schrader78dc1212023-08-16 18:17:47 -0700141 // The maximum time between when a message was sent and when it was logged.
142 // This is 0 if no message has been logged.
143 std::chrono::nanoseconds max_log_delay() const { return max_log_delay_; }
144 // The channel for longest logging delay, or -1 if no messages have been
145 // logged.
146 int max_log_delay_channel() const { return max_log_delay_channel_; }
147
Austin Schuhb06f03b2021-02-17 22:00:37 -0800148 void ResetStatisics();
149
150 // Rotates the log file(s), triggering new part files to be written for each
151 // log file.
152 void Rotate();
153
154 // Starts logging to files with the given naming scheme.
155 //
156 // log_start_uuid may be used to tie this log event to other log events across
157 // multiple nodes. The default (empty string) indicates there isn't one
158 // available.
159 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700160 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800161
Austin Schuh2d612c82023-07-17 13:37:48 -0700162 // Restarts logging using a new naming scheme. Intended for log rotation.
163 // Returns a unique_ptr to the prior log_namer instance. If provided,
164 // end_time is the time to log until. It must be in the past. Times before
165 // the last_synchronized_time are ignored.
Austin Schuh60e77942022-05-16 17:48:24 -0700166 std::unique_ptr<LogNamer> RestartLogging(
167 std::unique_ptr<LogNamer> log_namer,
Austin Schuh2d612c82023-07-17 13:37:48 -0700168 std::optional<UUID> log_start_uuid = std::nullopt,
169 std::optional<monotonic_clock::time_point> end_time = std::nullopt);
Brian Smartt03c00da2022-02-24 10:25:00 -0800170
Austin Schuhb06f03b2021-02-17 22:00:37 -0800171 // Stops logging. Ensures any messages through end_time make it into the log.
172 //
173 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
174 //
175 // Returns the LogNamer in case the caller wants to do anything else with it
176 // before destroying it.
177 std::unique_ptr<LogNamer> StopLogging(
178 aos::monotonic_clock::time_point end_time);
179
180 // Returns whether a log is currently being written.
181 bool is_started() const { return static_cast<bool>(log_namer_); }
182
Alexei Strots01395492023-03-20 13:59:56 -0700183 // Shortcut to call StartLogging with a MultiNodeFilesLogNamer when event
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700184 // processing starts.
colleen61276dc2023-06-01 09:23:29 -0700185 // Doesn't try to use odirect.
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700186 void StartLoggingOnRun(std::string base_name) {
187 event_loop_->OnRun([this, base_name]() {
Alexei Strots01395492023-03-20 13:59:56 -0700188 StartLogging(std::make_unique<MultiNodeFilesLogNamer>(
Austin Schuh5b728b72021-06-16 14:57:15 -0700189 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700190 });
191 }
192
Austin Schuh8721e732023-07-19 15:47:20 -0700193 // Returns the current log event UUID. This is randomly assigned when the log
194 // starts or restarts.
195 const UUID &log_event_uuid() const { return log_event_uuid_; }
196
Austin Schuhb06f03b2021-02-17 22:00:37 -0800197 private:
198 // Structure to track both a fetcher, and if the data fetched has been
199 // written. We may want to delay writing data to disk so that we don't let
200 // data get too far out of order when written to disk so we can avoid making
201 // it too hard to sort when reading.
202 struct FetcherStruct {
203 std::unique_ptr<RawFetcher> fetcher;
204 bool written = false;
205
206 // Channel index to log to.
207 int channel_index = -1;
208 const Channel *channel = nullptr;
209 const Node *timestamp_node = nullptr;
210
211 LogType log_type = LogType::kLogMessage;
212
213 // We fill out the metadata at construction, but the actual writers have to
214 // be updated each time we start logging. To avoid duplicating the complex
215 // logic determining whether each writer should be initialized, we just
216 // stash the answer in separate member variables.
217 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700218 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800219 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700220 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800221 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700222 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800223
224 // Node which this data is from, or -1 if it is unknown.
225 int data_node_index = -1;
226 // Node that this timestamp is for, or -1 if it is known.
227 int timestamp_node_index = -1;
228 // Node that the contents this contents_writer will log are from.
229 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700230
231 // If true, this message is being sent over a reliable channel.
232 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800233
234 // One of the following will be populated. If channel_reliable_contents is
235 // non zero size, it contains a mapping from the event loop channel (not the
236 // logged channel) to a bool telling us if that particular channel is
237 // reliable.
238 //
239 // If channel_reliable_contents is empty, reliable_contents will contain the
240 // same info for all contents logged here. This is the predominant case for
241 // split timestamp channels (the prefered approach).
242 bool reliable_contents = false;
243 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800244 };
245
246 // Vector mapping from the channel index from the event loop to the logged
247 // channel index.
248 std::vector<int> event_loop_to_logged_channel_index_;
249
Brian Smartt03c00da2022-02-24 10:25:00 -0800250 // Start/Restart write configuration into LogNamer space.
Austin Schuh60e77942022-05-16 17:48:24 -0700251 std::string WriteConfiguration(LogNamer *log_namer);
Brian Smartt03c00da2022-02-24 10:25:00 -0800252
Austin Schuh41f8df92022-04-15 11:45:52 -0700253 void WriteHeader(aos::monotonic_clock::time_point monotonic_start_time =
254 aos::monotonic_clock::min_time,
255 aos::realtime_clock::time_point realtime_start_time =
256 aos::realtime_clock::min_time);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800257
Austin Schuh73340842021-07-30 22:32:06 -0700258 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800259 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700260 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800261
Austin Schuhb06f03b2021-02-17 22:00:37 -0800262 bool MaybeUpdateTimestamp(
263 const Node *node, int node_index,
264 aos::monotonic_clock::time_point monotonic_start_time,
265 aos::realtime_clock::time_point realtime_start_time);
266
Austin Schuh30586902021-03-30 22:54:08 -0700267 void DoLogData(const monotonic_clock::time_point end_time,
268 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800269
270 void WriteMissingTimestamps();
271
Brian Smartt03c00da2022-02-24 10:25:00 -0800272 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
Austin Schuh60e77942022-05-16 17:48:24 -0700273 void WriteTimestamps(NewDataWriter *timestamps_writer,
274 const FetcherStruct &f);
Brian Smartt03c00da2022-02-24 10:25:00 -0800275 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
276
277 void WriteFetchedRecord(FetcherStruct &f);
278
Austin Schuh855f8932021-03-19 22:01:32 -0700279 // Fetches from each channel until all the data is logged. This is dangerous
280 // because it lets you log for more than 1 period. All calls need to verify
281 // that t isn't greater than 1 period in the future.
Austin Schuh08dba8f2023-05-01 08:29:30 -0700282 //
283 // Returns true if there is at least one message written, and also returns the
284 // timestamp of the newest record that any fetcher is pointing to, or min_time
285 // if there are no messages published on any logged channels.
286 std::pair<bool, monotonic_clock::time_point> LogUntil(
287 monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800288
289 void RecordFetchResult(aos::monotonic_clock::time_point start,
290 aos::monotonic_clock::time_point end, bool got_new,
291 FetcherStruct *fetcher);
292
293 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
294 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800295 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800296
Austin Schuhb06f03b2021-02-17 22:00:37 -0800297 EventLoop *const event_loop_;
298 // The configuration to place at the top of the log file.
299 const Configuration *const configuration_;
300
Austin Schuh5b728b72021-06-16 14:57:15 -0700301 // The node that is writing the log.
302 // For most cases, this is the same node as the node that is reading the
303 // messages. However, in some cases, these two nodes may be different. i.e. if
304 // one node reading and modifying the messages, and another node is listening
305 // and saving those messages to another log.
306 //
307 // node_ is a pointer to the writing node, and that node is guaranteed to be
308 // in configuration_ which is the configuration being written to the top of
309 // the log file.
310 const Node *const node_;
311 // The node_index_ is the index of the node in configuration_.
312 const size_t node_index_;
313
Austin Schuhb06f03b2021-02-17 22:00:37 -0800314 UUID log_event_uuid_ = UUID::Zero();
315 const UUID logger_instance_uuid_ = UUID::Random();
316 std::unique_ptr<LogNamer> log_namer_;
317 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700318 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800319
320 // Name to save in the log file. Defaults to hostname.
321 std::string name_;
Austin Schuhfa712682022-05-11 16:43:42 -0700322 std::string logger_sha1_;
323 std::string logger_version_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800324
Austin Schuh2f864452023-07-17 14:53:08 -0700325 // The callback to get called on each logged period. See
326 // set_on_logged_period() above for more details.
327 std::function<void(aos::monotonic_clock::time_point t)> on_logged_period_ =
328 [](aos::monotonic_clock::time_point) {};
Austin Schuhb06f03b2021-02-17 22:00:37 -0800329
330 std::chrono::nanoseconds max_message_fetch_time_ =
331 std::chrono::nanoseconds::zero();
332 int max_message_fetch_time_channel_ = -1;
333 int max_message_fetch_time_size_ = -1;
334 std::chrono::nanoseconds total_message_fetch_time_ =
335 std::chrono::nanoseconds::zero();
336 int total_message_fetch_count_ = 0;
337 int64_t total_message_fetch_bytes_ = 0;
338
Philipp Schrader78dc1212023-08-16 18:17:47 -0700339 std::chrono::nanoseconds max_log_delay_ = std::chrono::nanoseconds::zero();
340 int max_log_delay_channel_ = -1;
341
Austin Schuhb06f03b2021-02-17 22:00:37 -0800342 std::chrono::nanoseconds total_nop_fetch_time_ =
343 std::chrono::nanoseconds::zero();
344 int total_nop_fetch_count_ = 0;
345
346 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
347 int max_copy_time_channel_ = -1;
348 int max_copy_time_size_ = -1;
349 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
350 int total_copy_count_ = 0;
351 int64_t total_copy_bytes_ = 0;
352
353 std::vector<FetcherStruct> fetchers_;
354 TimerHandler *timer_handler_;
355
356 // Period to poll the channels.
357 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
358
359 // Last time that data was written for all channels to disk.
360 monotonic_clock::time_point last_synchronized_time_;
361
Austin Schuhb06f03b2021-02-17 22:00:37 -0800362 // If true, write the message header into a separate file.
363 bool separate_config_ = true;
364
365 // Fetcher for all the statistics from all the nodes.
366 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuh2d612c82023-07-17 13:37:48 -0700367
368 monotonic_clock::time_point log_until_time_ = monotonic_clock::min_time;
369
370 std::function<bool(const Context &)> fetch_next_if_fn_ =
371 [this](const Context &context) {
372 return context.monotonic_event_time < log_until_time_;
373 };
374
375 // Amount of time to run the logger behind now.
376 std::chrono::nanoseconds logging_delay_ = std::chrono::nanoseconds(0);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800377};
378
Stephan Pleinesd99b1ee2024-02-02 20:56:44 -0800379} // namespace aos::logger
Austin Schuhb06f03b2021-02-17 22:00:37 -0800380
381#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_