blob: ec02b7d35bca4cf8f48b1985344b290e907c1fda [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
20namespace aos {
21namespace logger {
22
Austin Schuh3b2b5b52023-07-05 11:36:46 -070023// Packs the provided configuration into the separate config LogFileHeader
24// container.
25aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> PackConfiguration(
26 const Configuration *const configuration);
27
Austin Schuhb06f03b2021-02-17 22:00:37 -080028// Logs all channels available in the event loop to disk every 100 ms.
29// Start by logging one message per channel to capture any state and
30// configuration that is sent rately on a channel and would affect execution.
31class Logger {
32 public:
33 // Constructs a logger.
34 // event_loop: The event loop used to read the messages.
35 // configuration: When provided, this is the configuration to log, and the
36 // configuration to use for the channel list to log. If not provided,
37 // this becomes the configuration from the event loop.
38 // should_log: When provided, a filter for channels to log. If not provided,
39 // all available channels are logged.
40 Logger(EventLoop *event_loop)
41 : Logger(event_loop, event_loop->configuration()) {}
42 Logger(EventLoop *event_loop, const Configuration *configuration)
43 : Logger(event_loop, configuration,
44 [](const Channel *) { return true; }) {}
45 Logger(EventLoop *event_loop, const Configuration *configuration,
46 std::function<bool(const Channel *)> should_log);
47 ~Logger();
48
49 // Overrides the name in the log file header.
50 void set_name(std::string_view name) { name_ = name; }
51
Austin Schuhfa712682022-05-11 16:43:42 -070052 void set_logger_sha1(std::string_view sha1) { logger_sha1_ = sha1; }
53 void set_logger_version(std::string_view version) {
54 logger_version_ = version;
55 }
56
Austin Schuh2f864452023-07-17 14:53:08 -070057 // Sets the callback to run *after* each period of data is logged. Defaults
58 // to doing nothing. The argument to the callback is the time which we just
59 // wrote until. This is not called when rotating or finishing logs.
Austin Schuhb06f03b2021-02-17 22:00:37 -080060 //
61 // This callback may safely do things like call Rotate().
Austin Schuh2f864452023-07-17 14:53:08 -070062 void set_on_logged_period(
63 std::function<void(aos::monotonic_clock::time_point t)>
64 on_logged_period) {
Austin Schuhb06f03b2021-02-17 22:00:37 -080065 on_logged_period_ = std::move(on_logged_period);
66 }
67
68 void set_separate_config(bool separate_config) {
69 separate_config_ = separate_config;
70 }
71
Austin Schuh2d612c82023-07-17 13:37:48 -070072 // Sets the amount to run the logger behind the current time. This lets us
73 // make decisions about rotating or stopping logging before something happens.
74 // Using this to start logging in the past isn't yet supported. This can be
75 // changed at runtime, but will only influence future writes, not what is
76 // already written.
77 void set_logging_delay(std::chrono::nanoseconds logging_delay) {
78 logging_delay_ = logging_delay;
79 }
Philipp Schrader78dc1212023-08-16 18:17:47 -070080 // Returns the current logging delay.
81 std::chrono::nanoseconds logging_delay() const { return logging_delay_; }
Austin Schuh2d612c82023-07-17 13:37:48 -070082
Austin Schuhb06f03b2021-02-17 22:00:37 -080083 // Sets the period between polling the data. Defaults to 100ms.
84 //
85 // Changing this while a set of files is being written may result in
86 // unreadable files.
87 void set_polling_period(std::chrono::nanoseconds polling_period) {
88 polling_period_ = polling_period;
89 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070090 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080091
Austin Schuh34f9e482021-03-31 22:54:18 -070092 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080093 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
94
95 // The maximum time for a single fetch which returned a message, or 0 if none
96 // of those have happened.
97 std::chrono::nanoseconds max_message_fetch_time() const {
98 return max_message_fetch_time_;
99 }
100 // The channel for that longest fetch which returned a message, or -1 if none
101 // of those have happened.
102 int max_message_fetch_time_channel() const {
103 return max_message_fetch_time_channel_;
104 }
105 // The size of the message returned by that longest fetch, or -1 if none of
106 // those have happened.
107 int max_message_fetch_time_size() const {
108 return max_message_fetch_time_size_;
109 }
110 // The total time spent fetching messages.
111 std::chrono::nanoseconds total_message_fetch_time() const {
112 return total_message_fetch_time_;
113 }
114 // The total number of fetch calls which returned messages.
115 int total_message_fetch_count() const { return total_message_fetch_count_; }
116 // The total number of bytes fetched.
117 int64_t total_message_fetch_bytes() const {
118 return total_message_fetch_bytes_;
119 }
120
121 // The total time spent in fetches which did not return a message.
122 std::chrono::nanoseconds total_nop_fetch_time() const {
123 return total_nop_fetch_time_;
124 }
125 // The total number of fetches which did not return a message.
126 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
127
128 // The maximum time for a single copy, or 0 if none of those have happened.
129 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
130 // The channel for that longest copy, or -1 if none of those have happened.
131 int max_copy_time_channel() const { return max_copy_time_channel_; }
132 // The size of the message for that longest copy, or -1 if none of those have
133 // happened.
134 int max_copy_time_size() const { return max_copy_time_size_; }
135 // The total time spent copying messages.
136 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
137 // The total number of messages copied.
138 int total_copy_count() const { return total_copy_count_; }
139 // The total number of bytes copied.
140 int64_t total_copy_bytes() const { return total_copy_bytes_; }
141
Philipp Schrader78dc1212023-08-16 18:17:47 -0700142 // The maximum time between when a message was sent and when it was logged.
143 // This is 0 if no message has been logged.
144 std::chrono::nanoseconds max_log_delay() const { return max_log_delay_; }
145 // The channel for longest logging delay, or -1 if no messages have been
146 // logged.
147 int max_log_delay_channel() const { return max_log_delay_channel_; }
148
Austin Schuhb06f03b2021-02-17 22:00:37 -0800149 void ResetStatisics();
150
151 // Rotates the log file(s), triggering new part files to be written for each
152 // log file.
153 void Rotate();
154
155 // Starts logging to files with the given naming scheme.
156 //
157 // log_start_uuid may be used to tie this log event to other log events across
158 // multiple nodes. The default (empty string) indicates there isn't one
159 // available.
160 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700161 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800162
Austin Schuh2d612c82023-07-17 13:37:48 -0700163 // Restarts logging using a new naming scheme. Intended for log rotation.
164 // Returns a unique_ptr to the prior log_namer instance. If provided,
165 // end_time is the time to log until. It must be in the past. Times before
166 // the last_synchronized_time are ignored.
Austin Schuh60e77942022-05-16 17:48:24 -0700167 std::unique_ptr<LogNamer> RestartLogging(
168 std::unique_ptr<LogNamer> log_namer,
Austin Schuh2d612c82023-07-17 13:37:48 -0700169 std::optional<UUID> log_start_uuid = std::nullopt,
170 std::optional<monotonic_clock::time_point> end_time = std::nullopt);
Brian Smartt03c00da2022-02-24 10:25:00 -0800171
Austin Schuhb06f03b2021-02-17 22:00:37 -0800172 // Stops logging. Ensures any messages through end_time make it into the log.
173 //
174 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
175 //
176 // Returns the LogNamer in case the caller wants to do anything else with it
177 // before destroying it.
178 std::unique_ptr<LogNamer> StopLogging(
179 aos::monotonic_clock::time_point end_time);
180
181 // Returns whether a log is currently being written.
182 bool is_started() const { return static_cast<bool>(log_namer_); }
183
Alexei Strots01395492023-03-20 13:59:56 -0700184 // Shortcut to call StartLogging with a MultiNodeFilesLogNamer when event
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700185 // processing starts.
colleen61276dc2023-06-01 09:23:29 -0700186 // Doesn't try to use odirect.
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700187 void StartLoggingOnRun(std::string base_name) {
188 event_loop_->OnRun([this, base_name]() {
Alexei Strots01395492023-03-20 13:59:56 -0700189 StartLogging(std::make_unique<MultiNodeFilesLogNamer>(
Austin Schuh5b728b72021-06-16 14:57:15 -0700190 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700191 });
192 }
193
Austin Schuh8721e732023-07-19 15:47:20 -0700194 // Returns the current log event UUID. This is randomly assigned when the log
195 // starts or restarts.
196 const UUID &log_event_uuid() const { return log_event_uuid_; }
197
Austin Schuhb06f03b2021-02-17 22:00:37 -0800198 private:
199 // Structure to track both a fetcher, and if the data fetched has been
200 // written. We may want to delay writing data to disk so that we don't let
201 // data get too far out of order when written to disk so we can avoid making
202 // it too hard to sort when reading.
203 struct FetcherStruct {
204 std::unique_ptr<RawFetcher> fetcher;
205 bool written = false;
206
207 // Channel index to log to.
208 int channel_index = -1;
209 const Channel *channel = nullptr;
210 const Node *timestamp_node = nullptr;
211
212 LogType log_type = LogType::kLogMessage;
213
214 // We fill out the metadata at construction, but the actual writers have to
215 // be updated each time we start logging. To avoid duplicating the complex
216 // logic determining whether each writer should be initialized, we just
217 // stash the answer in separate member variables.
218 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700219 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800220 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700221 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800222 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700223 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800224
225 // Node which this data is from, or -1 if it is unknown.
226 int data_node_index = -1;
227 // Node that this timestamp is for, or -1 if it is known.
228 int timestamp_node_index = -1;
229 // Node that the contents this contents_writer will log are from.
230 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700231
232 // If true, this message is being sent over a reliable channel.
233 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800234
235 // One of the following will be populated. If channel_reliable_contents is
236 // non zero size, it contains a mapping from the event loop channel (not the
237 // logged channel) to a bool telling us if that particular channel is
238 // reliable.
239 //
240 // If channel_reliable_contents is empty, reliable_contents will contain the
241 // same info for all contents logged here. This is the predominant case for
242 // split timestamp channels (the prefered approach).
243 bool reliable_contents = false;
244 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800245 };
246
247 // Vector mapping from the channel index from the event loop to the logged
248 // channel index.
249 std::vector<int> event_loop_to_logged_channel_index_;
250
Brian Smartt03c00da2022-02-24 10:25:00 -0800251 // Start/Restart write configuration into LogNamer space.
Austin Schuh60e77942022-05-16 17:48:24 -0700252 std::string WriteConfiguration(LogNamer *log_namer);
Brian Smartt03c00da2022-02-24 10:25:00 -0800253
Austin Schuh41f8df92022-04-15 11:45:52 -0700254 void WriteHeader(aos::monotonic_clock::time_point monotonic_start_time =
255 aos::monotonic_clock::min_time,
256 aos::realtime_clock::time_point realtime_start_time =
257 aos::realtime_clock::min_time);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800258
Austin Schuh73340842021-07-30 22:32:06 -0700259 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800260 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700261 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800262
Austin Schuhb06f03b2021-02-17 22:00:37 -0800263 bool MaybeUpdateTimestamp(
264 const Node *node, int node_index,
265 aos::monotonic_clock::time_point monotonic_start_time,
266 aos::realtime_clock::time_point realtime_start_time);
267
Austin Schuh30586902021-03-30 22:54:08 -0700268 void DoLogData(const monotonic_clock::time_point end_time,
269 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800270
271 void WriteMissingTimestamps();
272
Brian Smartt03c00da2022-02-24 10:25:00 -0800273 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
Austin Schuh60e77942022-05-16 17:48:24 -0700274 void WriteTimestamps(NewDataWriter *timestamps_writer,
275 const FetcherStruct &f);
Brian Smartt03c00da2022-02-24 10:25:00 -0800276 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
277
278 void WriteFetchedRecord(FetcherStruct &f);
279
Austin Schuh855f8932021-03-19 22:01:32 -0700280 // Fetches from each channel until all the data is logged. This is dangerous
281 // because it lets you log for more than 1 period. All calls need to verify
282 // that t isn't greater than 1 period in the future.
Austin Schuh08dba8f2023-05-01 08:29:30 -0700283 //
284 // Returns true if there is at least one message written, and also returns the
285 // timestamp of the newest record that any fetcher is pointing to, or min_time
286 // if there are no messages published on any logged channels.
287 std::pair<bool, monotonic_clock::time_point> LogUntil(
288 monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800289
290 void RecordFetchResult(aos::monotonic_clock::time_point start,
291 aos::monotonic_clock::time_point end, bool got_new,
292 FetcherStruct *fetcher);
293
294 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
295 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800296 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800297
Austin Schuhb06f03b2021-02-17 22:00:37 -0800298 EventLoop *const event_loop_;
299 // The configuration to place at the top of the log file.
300 const Configuration *const configuration_;
301
Austin Schuh5b728b72021-06-16 14:57:15 -0700302 // The node that is writing the log.
303 // For most cases, this is the same node as the node that is reading the
304 // messages. However, in some cases, these two nodes may be different. i.e. if
305 // one node reading and modifying the messages, and another node is listening
306 // and saving those messages to another log.
307 //
308 // node_ is a pointer to the writing node, and that node is guaranteed to be
309 // in configuration_ which is the configuration being written to the top of
310 // the log file.
311 const Node *const node_;
312 // The node_index_ is the index of the node in configuration_.
313 const size_t node_index_;
314
Austin Schuhb06f03b2021-02-17 22:00:37 -0800315 UUID log_event_uuid_ = UUID::Zero();
316 const UUID logger_instance_uuid_ = UUID::Random();
317 std::unique_ptr<LogNamer> log_namer_;
318 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700319 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800320
321 // Name to save in the log file. Defaults to hostname.
322 std::string name_;
Austin Schuhfa712682022-05-11 16:43:42 -0700323 std::string logger_sha1_;
324 std::string logger_version_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800325
Austin Schuh2f864452023-07-17 14:53:08 -0700326 // The callback to get called on each logged period. See
327 // set_on_logged_period() above for more details.
328 std::function<void(aos::monotonic_clock::time_point t)> on_logged_period_ =
329 [](aos::monotonic_clock::time_point) {};
Austin Schuhb06f03b2021-02-17 22:00:37 -0800330
331 std::chrono::nanoseconds max_message_fetch_time_ =
332 std::chrono::nanoseconds::zero();
333 int max_message_fetch_time_channel_ = -1;
334 int max_message_fetch_time_size_ = -1;
335 std::chrono::nanoseconds total_message_fetch_time_ =
336 std::chrono::nanoseconds::zero();
337 int total_message_fetch_count_ = 0;
338 int64_t total_message_fetch_bytes_ = 0;
339
Philipp Schrader78dc1212023-08-16 18:17:47 -0700340 std::chrono::nanoseconds max_log_delay_ = std::chrono::nanoseconds::zero();
341 int max_log_delay_channel_ = -1;
342
Austin Schuhb06f03b2021-02-17 22:00:37 -0800343 std::chrono::nanoseconds total_nop_fetch_time_ =
344 std::chrono::nanoseconds::zero();
345 int total_nop_fetch_count_ = 0;
346
347 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
348 int max_copy_time_channel_ = -1;
349 int max_copy_time_size_ = -1;
350 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
351 int total_copy_count_ = 0;
352 int64_t total_copy_bytes_ = 0;
353
354 std::vector<FetcherStruct> fetchers_;
355 TimerHandler *timer_handler_;
356
357 // Period to poll the channels.
358 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
359
360 // Last time that data was written for all channels to disk.
361 monotonic_clock::time_point last_synchronized_time_;
362
Austin Schuhb06f03b2021-02-17 22:00:37 -0800363 // If true, write the message header into a separate file.
364 bool separate_config_ = true;
365
366 // Fetcher for all the statistics from all the nodes.
367 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuh2d612c82023-07-17 13:37:48 -0700368
369 monotonic_clock::time_point log_until_time_ = monotonic_clock::min_time;
370
371 std::function<bool(const Context &)> fetch_next_if_fn_ =
372 [this](const Context &context) {
373 return context.monotonic_event_time < log_until_time_;
374 };
375
376 // Amount of time to run the logger behind now.
377 std::chrono::nanoseconds logging_delay_ = std::chrono::nanoseconds(0);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800378};
379
380} // namespace logger
381} // namespace aos
382
383#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_