blob: 3d3d7f22ed29e8b91a11f054fa10c97d821fe766 [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 Schuhb06f03b2021-02-17 22:00:37 -080057 // Sets the callback to run after each period of data is logged. Defaults to
58 // doing nothing.
59 //
60 // This callback may safely do things like call Rotate().
61 void set_on_logged_period(std::function<void()> on_logged_period) {
62 on_logged_period_ = std::move(on_logged_period);
63 }
64
65 void set_separate_config(bool separate_config) {
66 separate_config_ = separate_config;
67 }
68
Austin Schuh2d612c82023-07-17 13:37:48 -070069 // Sets the amount to run the logger behind the current time. This lets us
70 // make decisions about rotating or stopping logging before something happens.
71 // Using this to start logging in the past isn't yet supported. This can be
72 // changed at runtime, but will only influence future writes, not what is
73 // already written.
74 void set_logging_delay(std::chrono::nanoseconds logging_delay) {
75 logging_delay_ = logging_delay;
76 }
77
Austin Schuhb06f03b2021-02-17 22:00:37 -080078 // Sets the period between polling the data. Defaults to 100ms.
79 //
80 // Changing this while a set of files is being written may result in
81 // unreadable files.
82 void set_polling_period(std::chrono::nanoseconds polling_period) {
83 polling_period_ = polling_period;
84 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070085 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080086
Austin Schuh34f9e482021-03-31 22:54:18 -070087 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080088 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
89
90 // The maximum time for a single fetch which returned a message, or 0 if none
91 // of those have happened.
92 std::chrono::nanoseconds max_message_fetch_time() const {
93 return max_message_fetch_time_;
94 }
95 // The channel for that longest fetch which returned a message, or -1 if none
96 // of those have happened.
97 int max_message_fetch_time_channel() const {
98 return max_message_fetch_time_channel_;
99 }
100 // The size of the message returned by that longest fetch, or -1 if none of
101 // those have happened.
102 int max_message_fetch_time_size() const {
103 return max_message_fetch_time_size_;
104 }
105 // The total time spent fetching messages.
106 std::chrono::nanoseconds total_message_fetch_time() const {
107 return total_message_fetch_time_;
108 }
109 // The total number of fetch calls which returned messages.
110 int total_message_fetch_count() const { return total_message_fetch_count_; }
111 // The total number of bytes fetched.
112 int64_t total_message_fetch_bytes() const {
113 return total_message_fetch_bytes_;
114 }
115
116 // The total time spent in fetches which did not return a message.
117 std::chrono::nanoseconds total_nop_fetch_time() const {
118 return total_nop_fetch_time_;
119 }
120 // The total number of fetches which did not return a message.
121 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
122
123 // The maximum time for a single copy, or 0 if none of those have happened.
124 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
125 // The channel for that longest copy, or -1 if none of those have happened.
126 int max_copy_time_channel() const { return max_copy_time_channel_; }
127 // The size of the message for that longest copy, or -1 if none of those have
128 // happened.
129 int max_copy_time_size() const { return max_copy_time_size_; }
130 // The total time spent copying messages.
131 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
132 // The total number of messages copied.
133 int total_copy_count() const { return total_copy_count_; }
134 // The total number of bytes copied.
135 int64_t total_copy_bytes() const { return total_copy_bytes_; }
136
137 void ResetStatisics();
138
139 // Rotates the log file(s), triggering new part files to be written for each
140 // log file.
141 void Rotate();
142
143 // Starts logging to files with the given naming scheme.
144 //
145 // log_start_uuid may be used to tie this log event to other log events across
146 // multiple nodes. The default (empty string) indicates there isn't one
147 // available.
148 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700149 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800150
Austin Schuh2d612c82023-07-17 13:37:48 -0700151 // Restarts logging using a new naming scheme. Intended for log rotation.
152 // Returns a unique_ptr to the prior log_namer instance. If provided,
153 // end_time is the time to log until. It must be in the past. Times before
154 // the last_synchronized_time are ignored.
Austin Schuh60e77942022-05-16 17:48:24 -0700155 std::unique_ptr<LogNamer> RestartLogging(
156 std::unique_ptr<LogNamer> log_namer,
Austin Schuh2d612c82023-07-17 13:37:48 -0700157 std::optional<UUID> log_start_uuid = std::nullopt,
158 std::optional<monotonic_clock::time_point> end_time = std::nullopt);
Brian Smartt03c00da2022-02-24 10:25:00 -0800159
Austin Schuhb06f03b2021-02-17 22:00:37 -0800160 // Stops logging. Ensures any messages through end_time make it into the log.
161 //
162 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
163 //
164 // Returns the LogNamer in case the caller wants to do anything else with it
165 // before destroying it.
166 std::unique_ptr<LogNamer> StopLogging(
167 aos::monotonic_clock::time_point end_time);
168
169 // Returns whether a log is currently being written.
170 bool is_started() const { return static_cast<bool>(log_namer_); }
171
Alexei Strots01395492023-03-20 13:59:56 -0700172 // Shortcut to call StartLogging with a MultiNodeFilesLogNamer when event
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700173 // processing starts.
colleen61276dc2023-06-01 09:23:29 -0700174 // Doesn't try to use odirect.
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700175 void StartLoggingOnRun(std::string base_name) {
176 event_loop_->OnRun([this, base_name]() {
Alexei Strots01395492023-03-20 13:59:56 -0700177 StartLogging(std::make_unique<MultiNodeFilesLogNamer>(
Austin Schuh5b728b72021-06-16 14:57:15 -0700178 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700179 });
180 }
181
Austin Schuhb06f03b2021-02-17 22:00:37 -0800182 private:
183 // Structure to track both a fetcher, and if the data fetched has been
184 // written. We may want to delay writing data to disk so that we don't let
185 // data get too far out of order when written to disk so we can avoid making
186 // it too hard to sort when reading.
187 struct FetcherStruct {
188 std::unique_ptr<RawFetcher> fetcher;
189 bool written = false;
190
191 // Channel index to log to.
192 int channel_index = -1;
193 const Channel *channel = nullptr;
194 const Node *timestamp_node = nullptr;
195
196 LogType log_type = LogType::kLogMessage;
197
198 // We fill out the metadata at construction, but the actual writers have to
199 // be updated each time we start logging. To avoid duplicating the complex
200 // logic determining whether each writer should be initialized, we just
201 // stash the answer in separate member variables.
202 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700203 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800204 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700205 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800206 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700207 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800208
209 // Node which this data is from, or -1 if it is unknown.
210 int data_node_index = -1;
211 // Node that this timestamp is for, or -1 if it is known.
212 int timestamp_node_index = -1;
213 // Node that the contents this contents_writer will log are from.
214 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700215
216 // If true, this message is being sent over a reliable channel.
217 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800218
219 // One of the following will be populated. If channel_reliable_contents is
220 // non zero size, it contains a mapping from the event loop channel (not the
221 // logged channel) to a bool telling us if that particular channel is
222 // reliable.
223 //
224 // If channel_reliable_contents is empty, reliable_contents will contain the
225 // same info for all contents logged here. This is the predominant case for
226 // split timestamp channels (the prefered approach).
227 bool reliable_contents = false;
228 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800229 };
230
231 // Vector mapping from the channel index from the event loop to the logged
232 // channel index.
233 std::vector<int> event_loop_to_logged_channel_index_;
234
Brian Smartt03c00da2022-02-24 10:25:00 -0800235 // Start/Restart write configuration into LogNamer space.
Austin Schuh60e77942022-05-16 17:48:24 -0700236 std::string WriteConfiguration(LogNamer *log_namer);
Brian Smartt03c00da2022-02-24 10:25:00 -0800237
Austin Schuh41f8df92022-04-15 11:45:52 -0700238 void WriteHeader(aos::monotonic_clock::time_point monotonic_start_time =
239 aos::monotonic_clock::min_time,
240 aos::realtime_clock::time_point realtime_start_time =
241 aos::realtime_clock::min_time);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800242
Austin Schuh73340842021-07-30 22:32:06 -0700243 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800244 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700245 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800246
Austin Schuhb06f03b2021-02-17 22:00:37 -0800247 bool MaybeUpdateTimestamp(
248 const Node *node, int node_index,
249 aos::monotonic_clock::time_point monotonic_start_time,
250 aos::realtime_clock::time_point realtime_start_time);
251
Austin Schuh30586902021-03-30 22:54:08 -0700252 void DoLogData(const monotonic_clock::time_point end_time,
253 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800254
255 void WriteMissingTimestamps();
256
Brian Smartt03c00da2022-02-24 10:25:00 -0800257 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
Austin Schuh60e77942022-05-16 17:48:24 -0700258 void WriteTimestamps(NewDataWriter *timestamps_writer,
259 const FetcherStruct &f);
Brian Smartt03c00da2022-02-24 10:25:00 -0800260 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
261
262 void WriteFetchedRecord(FetcherStruct &f);
263
Austin Schuh855f8932021-03-19 22:01:32 -0700264 // Fetches from each channel until all the data is logged. This is dangerous
265 // because it lets you log for more than 1 period. All calls need to verify
266 // that t isn't greater than 1 period in the future.
Austin Schuh08dba8f2023-05-01 08:29:30 -0700267 //
268 // Returns true if there is at least one message written, and also returns the
269 // timestamp of the newest record that any fetcher is pointing to, or min_time
270 // if there are no messages published on any logged channels.
271 std::pair<bool, monotonic_clock::time_point> LogUntil(
272 monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800273
274 void RecordFetchResult(aos::monotonic_clock::time_point start,
275 aos::monotonic_clock::time_point end, bool got_new,
276 FetcherStruct *fetcher);
277
278 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
279 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800280 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800281
Austin Schuhb06f03b2021-02-17 22:00:37 -0800282 EventLoop *const event_loop_;
283 // The configuration to place at the top of the log file.
284 const Configuration *const configuration_;
285
Austin Schuh5b728b72021-06-16 14:57:15 -0700286 // The node that is writing the log.
287 // For most cases, this is the same node as the node that is reading the
288 // messages. However, in some cases, these two nodes may be different. i.e. if
289 // one node reading and modifying the messages, and another node is listening
290 // and saving those messages to another log.
291 //
292 // node_ is a pointer to the writing node, and that node is guaranteed to be
293 // in configuration_ which is the configuration being written to the top of
294 // the log file.
295 const Node *const node_;
296 // The node_index_ is the index of the node in configuration_.
297 const size_t node_index_;
298
Austin Schuhb06f03b2021-02-17 22:00:37 -0800299 UUID log_event_uuid_ = UUID::Zero();
300 const UUID logger_instance_uuid_ = UUID::Random();
301 std::unique_ptr<LogNamer> log_namer_;
302 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700303 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800304
305 // Name to save in the log file. Defaults to hostname.
306 std::string name_;
Austin Schuhfa712682022-05-11 16:43:42 -0700307 std::string logger_sha1_;
308 std::string logger_version_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800309
310 std::function<void()> on_logged_period_ = []() {};
311
312 std::chrono::nanoseconds max_message_fetch_time_ =
313 std::chrono::nanoseconds::zero();
314 int max_message_fetch_time_channel_ = -1;
315 int max_message_fetch_time_size_ = -1;
316 std::chrono::nanoseconds total_message_fetch_time_ =
317 std::chrono::nanoseconds::zero();
318 int total_message_fetch_count_ = 0;
319 int64_t total_message_fetch_bytes_ = 0;
320
321 std::chrono::nanoseconds total_nop_fetch_time_ =
322 std::chrono::nanoseconds::zero();
323 int total_nop_fetch_count_ = 0;
324
325 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
326 int max_copy_time_channel_ = -1;
327 int max_copy_time_size_ = -1;
328 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
329 int total_copy_count_ = 0;
330 int64_t total_copy_bytes_ = 0;
331
332 std::vector<FetcherStruct> fetchers_;
333 TimerHandler *timer_handler_;
334
335 // Period to poll the channels.
336 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
337
338 // Last time that data was written for all channels to disk.
339 monotonic_clock::time_point last_synchronized_time_;
340
Austin Schuhb06f03b2021-02-17 22:00:37 -0800341 // If true, write the message header into a separate file.
342 bool separate_config_ = true;
343
344 // Fetcher for all the statistics from all the nodes.
345 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuh2d612c82023-07-17 13:37:48 -0700346
347 monotonic_clock::time_point log_until_time_ = monotonic_clock::min_time;
348
349 std::function<bool(const Context &)> fetch_next_if_fn_ =
350 [this](const Context &context) {
351 return context.monotonic_event_time < log_until_time_;
352 };
353
354 // Amount of time to run the logger behind now.
355 std::chrono::nanoseconds logging_delay_ = std::chrono::nanoseconds(0);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800356};
357
358} // namespace logger
359} // namespace aos
360
361#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_