blob: 6fb1bfaa1fc9c4ea5bae0313682b9b1588a88956 [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 }
80
Austin Schuhb06f03b2021-02-17 22:00:37 -080081 // Sets the period between polling the data. Defaults to 100ms.
82 //
83 // Changing this while a set of files is being written may result in
84 // unreadable files.
85 void set_polling_period(std::chrono::nanoseconds polling_period) {
86 polling_period_ = polling_period;
87 }
Austin Schuh29cf4e52021-03-31 22:51:35 -070088 std::chrono::nanoseconds polling_period() const { return polling_period_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080089
Austin Schuh34f9e482021-03-31 22:54:18 -070090 std::optional<UUID> log_start_uuid() const { return log_start_uuid_; }
Austin Schuhb06f03b2021-02-17 22:00:37 -080091 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
92
93 // The maximum time for a single fetch which returned a message, or 0 if none
94 // of those have happened.
95 std::chrono::nanoseconds max_message_fetch_time() const {
96 return max_message_fetch_time_;
97 }
98 // The channel for that longest fetch which returned a message, or -1 if none
99 // of those have happened.
100 int max_message_fetch_time_channel() const {
101 return max_message_fetch_time_channel_;
102 }
103 // The size of the message returned by that longest fetch, or -1 if none of
104 // those have happened.
105 int max_message_fetch_time_size() const {
106 return max_message_fetch_time_size_;
107 }
108 // The total time spent fetching messages.
109 std::chrono::nanoseconds total_message_fetch_time() const {
110 return total_message_fetch_time_;
111 }
112 // The total number of fetch calls which returned messages.
113 int total_message_fetch_count() const { return total_message_fetch_count_; }
114 // The total number of bytes fetched.
115 int64_t total_message_fetch_bytes() const {
116 return total_message_fetch_bytes_;
117 }
118
119 // The total time spent in fetches which did not return a message.
120 std::chrono::nanoseconds total_nop_fetch_time() const {
121 return total_nop_fetch_time_;
122 }
123 // The total number of fetches which did not return a message.
124 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
125
126 // The maximum time for a single copy, or 0 if none of those have happened.
127 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
128 // The channel for that longest copy, or -1 if none of those have happened.
129 int max_copy_time_channel() const { return max_copy_time_channel_; }
130 // The size of the message for that longest copy, or -1 if none of those have
131 // happened.
132 int max_copy_time_size() const { return max_copy_time_size_; }
133 // The total time spent copying messages.
134 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
135 // The total number of messages copied.
136 int total_copy_count() const { return total_copy_count_; }
137 // The total number of bytes copied.
138 int64_t total_copy_bytes() const { return total_copy_bytes_; }
139
140 void ResetStatisics();
141
142 // Rotates the log file(s), triggering new part files to be written for each
143 // log file.
144 void Rotate();
145
146 // Starts logging to files with the given naming scheme.
147 //
148 // log_start_uuid may be used to tie this log event to other log events across
149 // multiple nodes. The default (empty string) indicates there isn't one
150 // available.
151 void StartLogging(std::unique_ptr<LogNamer> log_namer,
Austin Schuh34f9e482021-03-31 22:54:18 -0700152 std::optional<UUID> log_start_uuid = std::nullopt);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800153
Austin Schuh2d612c82023-07-17 13:37:48 -0700154 // Restarts logging using a new naming scheme. Intended for log rotation.
155 // Returns a unique_ptr to the prior log_namer instance. If provided,
156 // end_time is the time to log until. It must be in the past. Times before
157 // the last_synchronized_time are ignored.
Austin Schuh60e77942022-05-16 17:48:24 -0700158 std::unique_ptr<LogNamer> RestartLogging(
159 std::unique_ptr<LogNamer> log_namer,
Austin Schuh2d612c82023-07-17 13:37:48 -0700160 std::optional<UUID> log_start_uuid = std::nullopt,
161 std::optional<monotonic_clock::time_point> end_time = std::nullopt);
Brian Smartt03c00da2022-02-24 10:25:00 -0800162
Austin Schuhb06f03b2021-02-17 22:00:37 -0800163 // Stops logging. Ensures any messages through end_time make it into the log.
164 //
165 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
166 //
167 // Returns the LogNamer in case the caller wants to do anything else with it
168 // before destroying it.
169 std::unique_ptr<LogNamer> StopLogging(
170 aos::monotonic_clock::time_point end_time);
171
172 // Returns whether a log is currently being written.
173 bool is_started() const { return static_cast<bool>(log_namer_); }
174
Alexei Strots01395492023-03-20 13:59:56 -0700175 // Shortcut to call StartLogging with a MultiNodeFilesLogNamer when event
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700176 // processing starts.
colleen61276dc2023-06-01 09:23:29 -0700177 // Doesn't try to use odirect.
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700178 void StartLoggingOnRun(std::string base_name) {
179 event_loop_->OnRun([this, base_name]() {
Alexei Strots01395492023-03-20 13:59:56 -0700180 StartLogging(std::make_unique<MultiNodeFilesLogNamer>(
Austin Schuh5b728b72021-06-16 14:57:15 -0700181 base_name, configuration_, event_loop_, node_));
Austin Schuh5b6b3bc2021-03-31 22:55:06 -0700182 });
183 }
184
Austin Schuhb06f03b2021-02-17 22:00:37 -0800185 private:
186 // Structure to track both a fetcher, and if the data fetched has been
187 // written. We may want to delay writing data to disk so that we don't let
188 // data get too far out of order when written to disk so we can avoid making
189 // it too hard to sort when reading.
190 struct FetcherStruct {
191 std::unique_ptr<RawFetcher> fetcher;
192 bool written = false;
193
194 // Channel index to log to.
195 int channel_index = -1;
196 const Channel *channel = nullptr;
197 const Node *timestamp_node = nullptr;
198
199 LogType log_type = LogType::kLogMessage;
200
201 // We fill out the metadata at construction, but the actual writers have to
202 // be updated each time we start logging. To avoid duplicating the complex
203 // logic determining whether each writer should be initialized, we just
204 // stash the answer in separate member variables.
205 bool wants_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700206 NewDataWriter *writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800207 bool wants_timestamp_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700208 NewDataWriter *timestamp_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800209 bool wants_contents_writer = false;
Austin Schuhb8bca732021-07-30 22:32:00 -0700210 NewDataWriter *contents_writer = nullptr;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800211
212 // Node which this data is from, or -1 if it is unknown.
213 int data_node_index = -1;
214 // Node that this timestamp is for, or -1 if it is known.
215 int timestamp_node_index = -1;
216 // Node that the contents this contents_writer will log are from.
217 int contents_node_index = -1;
Austin Schuh72211ae2021-08-05 14:02:30 -0700218
219 // If true, this message is being sent over a reliable channel.
220 bool reliable_forwarding = false;
Austin Schuh01f3b392022-01-25 20:03:09 -0800221
222 // One of the following will be populated. If channel_reliable_contents is
223 // non zero size, it contains a mapping from the event loop channel (not the
224 // logged channel) to a bool telling us if that particular channel is
225 // reliable.
226 //
227 // If channel_reliable_contents is empty, reliable_contents will contain the
228 // same info for all contents logged here. This is the predominant case for
229 // split timestamp channels (the prefered approach).
230 bool reliable_contents = false;
231 std::vector<bool> channel_reliable_contents;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800232 };
233
234 // Vector mapping from the channel index from the event loop to the logged
235 // channel index.
236 std::vector<int> event_loop_to_logged_channel_index_;
237
Brian Smartt03c00da2022-02-24 10:25:00 -0800238 // Start/Restart write configuration into LogNamer space.
Austin Schuh60e77942022-05-16 17:48:24 -0700239 std::string WriteConfiguration(LogNamer *log_namer);
Brian Smartt03c00da2022-02-24 10:25:00 -0800240
Austin Schuh41f8df92022-04-15 11:45:52 -0700241 void WriteHeader(aos::monotonic_clock::time_point monotonic_start_time =
242 aos::monotonic_clock::min_time,
243 aos::realtime_clock::time_point realtime_start_time =
244 aos::realtime_clock::min_time);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800245
Austin Schuh73340842021-07-30 22:32:06 -0700246 // Makes a template header for all the follower nodes.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800247 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
Austin Schuh73340842021-07-30 22:32:06 -0700248 std::string_view config_sha256);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800249
Austin Schuhb06f03b2021-02-17 22:00:37 -0800250 bool MaybeUpdateTimestamp(
251 const Node *node, int node_index,
252 aos::monotonic_clock::time_point monotonic_start_time,
253 aos::realtime_clock::time_point realtime_start_time);
254
Austin Schuh30586902021-03-30 22:54:08 -0700255 void DoLogData(const monotonic_clock::time_point end_time,
256 bool run_on_logged);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800257
258 void WriteMissingTimestamps();
259
Brian Smartt03c00da2022-02-24 10:25:00 -0800260 void WriteData(NewDataWriter *writer, const FetcherStruct &f);
Austin Schuh60e77942022-05-16 17:48:24 -0700261 void WriteTimestamps(NewDataWriter *timestamps_writer,
262 const FetcherStruct &f);
Brian Smartt03c00da2022-02-24 10:25:00 -0800263 void WriteContent(NewDataWriter *contents_writer, const FetcherStruct &f);
264
265 void WriteFetchedRecord(FetcherStruct &f);
266
Austin Schuh855f8932021-03-19 22:01:32 -0700267 // Fetches from each channel until all the data is logged. This is dangerous
268 // because it lets you log for more than 1 period. All calls need to verify
269 // that t isn't greater than 1 period in the future.
Austin Schuh08dba8f2023-05-01 08:29:30 -0700270 //
271 // Returns true if there is at least one message written, and also returns the
272 // timestamp of the newest record that any fetcher is pointing to, or min_time
273 // if there are no messages published on any logged channels.
274 std::pair<bool, monotonic_clock::time_point> LogUntil(
275 monotonic_clock::time_point t);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800276
277 void RecordFetchResult(aos::monotonic_clock::time_point start,
278 aos::monotonic_clock::time_point end, bool got_new,
279 FetcherStruct *fetcher);
280
281 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
282 aos::monotonic_clock::time_point end,
Brian Smartt03c00da2022-02-24 10:25:00 -0800283 const FetcherStruct &fetcher);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800284
Austin Schuhb06f03b2021-02-17 22:00:37 -0800285 EventLoop *const event_loop_;
286 // The configuration to place at the top of the log file.
287 const Configuration *const configuration_;
288
Austin Schuh5b728b72021-06-16 14:57:15 -0700289 // The node that is writing the log.
290 // For most cases, this is the same node as the node that is reading the
291 // messages. However, in some cases, these two nodes may be different. i.e. if
292 // one node reading and modifying the messages, and another node is listening
293 // and saving those messages to another log.
294 //
295 // node_ is a pointer to the writing node, and that node is guaranteed to be
296 // in configuration_ which is the configuration being written to the top of
297 // the log file.
298 const Node *const node_;
299 // The node_index_ is the index of the node in configuration_.
300 const size_t node_index_;
301
Austin Schuhb06f03b2021-02-17 22:00:37 -0800302 UUID log_event_uuid_ = UUID::Zero();
303 const UUID logger_instance_uuid_ = UUID::Random();
304 std::unique_ptr<LogNamer> log_namer_;
305 // Empty indicates there isn't one.
Austin Schuh34f9e482021-03-31 22:54:18 -0700306 std::optional<UUID> log_start_uuid_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800307
308 // Name to save in the log file. Defaults to hostname.
309 std::string name_;
Austin Schuhfa712682022-05-11 16:43:42 -0700310 std::string logger_sha1_;
311 std::string logger_version_;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800312
Austin Schuh2f864452023-07-17 14:53:08 -0700313 // The callback to get called on each logged period. See
314 // set_on_logged_period() above for more details.
315 std::function<void(aos::monotonic_clock::time_point t)> on_logged_period_ =
316 [](aos::monotonic_clock::time_point) {};
Austin Schuhb06f03b2021-02-17 22:00:37 -0800317
318 std::chrono::nanoseconds max_message_fetch_time_ =
319 std::chrono::nanoseconds::zero();
320 int max_message_fetch_time_channel_ = -1;
321 int max_message_fetch_time_size_ = -1;
322 std::chrono::nanoseconds total_message_fetch_time_ =
323 std::chrono::nanoseconds::zero();
324 int total_message_fetch_count_ = 0;
325 int64_t total_message_fetch_bytes_ = 0;
326
327 std::chrono::nanoseconds total_nop_fetch_time_ =
328 std::chrono::nanoseconds::zero();
329 int total_nop_fetch_count_ = 0;
330
331 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
332 int max_copy_time_channel_ = -1;
333 int max_copy_time_size_ = -1;
334 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
335 int total_copy_count_ = 0;
336 int64_t total_copy_bytes_ = 0;
337
338 std::vector<FetcherStruct> fetchers_;
339 TimerHandler *timer_handler_;
340
341 // Period to poll the channels.
342 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
343
344 // Last time that data was written for all channels to disk.
345 monotonic_clock::time_point last_synchronized_time_;
346
Austin Schuhb06f03b2021-02-17 22:00:37 -0800347 // If true, write the message header into a separate file.
348 bool separate_config_ = true;
349
350 // Fetcher for all the statistics from all the nodes.
351 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
Austin Schuh2d612c82023-07-17 13:37:48 -0700352
353 monotonic_clock::time_point log_until_time_ = monotonic_clock::min_time;
354
355 std::function<bool(const Context &)> fetch_next_if_fn_ =
356 [this](const Context &context) {
357 return context.monotonic_event_time < log_until_time_;
358 };
359
360 // Amount of time to run the logger behind now.
361 std::chrono::nanoseconds logging_delay_ = std::chrono::nanoseconds(0);
Austin Schuhb06f03b2021-02-17 22:00:37 -0800362};
363
364} // namespace logger
365} // namespace aos
366
367#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_