blob: 992633adf378c474eadab0c977e729be55d7e791 [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 }
65
66 std::string_view log_start_uuid() const { return log_start_uuid_; }
67 UUID logger_instance_uuid() const { return logger_instance_uuid_; }
68
69 // The maximum time for a single fetch which returned a message, or 0 if none
70 // of those have happened.
71 std::chrono::nanoseconds max_message_fetch_time() const {
72 return max_message_fetch_time_;
73 }
74 // The channel for that longest fetch which returned a message, or -1 if none
75 // of those have happened.
76 int max_message_fetch_time_channel() const {
77 return max_message_fetch_time_channel_;
78 }
79 // The size of the message returned by that longest fetch, or -1 if none of
80 // those have happened.
81 int max_message_fetch_time_size() const {
82 return max_message_fetch_time_size_;
83 }
84 // The total time spent fetching messages.
85 std::chrono::nanoseconds total_message_fetch_time() const {
86 return total_message_fetch_time_;
87 }
88 // The total number of fetch calls which returned messages.
89 int total_message_fetch_count() const { return total_message_fetch_count_; }
90 // The total number of bytes fetched.
91 int64_t total_message_fetch_bytes() const {
92 return total_message_fetch_bytes_;
93 }
94
95 // The total time spent in fetches which did not return a message.
96 std::chrono::nanoseconds total_nop_fetch_time() const {
97 return total_nop_fetch_time_;
98 }
99 // The total number of fetches which did not return a message.
100 int total_nop_fetch_count() const { return total_nop_fetch_count_; }
101
102 // The maximum time for a single copy, or 0 if none of those have happened.
103 std::chrono::nanoseconds max_copy_time() const { return max_copy_time_; }
104 // The channel for that longest copy, or -1 if none of those have happened.
105 int max_copy_time_channel() const { return max_copy_time_channel_; }
106 // The size of the message for that longest copy, or -1 if none of those have
107 // happened.
108 int max_copy_time_size() const { return max_copy_time_size_; }
109 // The total time spent copying messages.
110 std::chrono::nanoseconds total_copy_time() const { return total_copy_time_; }
111 // The total number of messages copied.
112 int total_copy_count() const { return total_copy_count_; }
113 // The total number of bytes copied.
114 int64_t total_copy_bytes() const { return total_copy_bytes_; }
115
116 void ResetStatisics();
117
118 // Rotates the log file(s), triggering new part files to be written for each
119 // log file.
120 void Rotate();
121
122 // Starts logging to files with the given naming scheme.
123 //
124 // log_start_uuid may be used to tie this log event to other log events across
125 // multiple nodes. The default (empty string) indicates there isn't one
126 // available.
127 void StartLogging(std::unique_ptr<LogNamer> log_namer,
128 std::string_view log_start_uuid = "");
129
130 // Stops logging. Ensures any messages through end_time make it into the log.
131 //
132 // If you want to stop ASAP, pass min_time to avoid reading any more messages.
133 //
134 // Returns the LogNamer in case the caller wants to do anything else with it
135 // before destroying it.
136 std::unique_ptr<LogNamer> StopLogging(
137 aos::monotonic_clock::time_point end_time);
138
139 // Returns whether a log is currently being written.
140 bool is_started() const { return static_cast<bool>(log_namer_); }
141
142 // Shortcut to call StartLogging with a LocalLogNamer when event processing
143 // starts.
144 void StartLoggingLocalNamerOnRun(std::string base_name) {
145 event_loop_->OnRun([this, base_name]() {
146 StartLogging(
147 std::make_unique<LocalLogNamer>(base_name, event_loop_->node()));
148 });
149 }
150
151 private:
152 // Structure to track both a fetcher, and if the data fetched has been
153 // written. We may want to delay writing data to disk so that we don't let
154 // data get too far out of order when written to disk so we can avoid making
155 // it too hard to sort when reading.
156 struct FetcherStruct {
157 std::unique_ptr<RawFetcher> fetcher;
158 bool written = false;
159
160 // Channel index to log to.
161 int channel_index = -1;
162 const Channel *channel = nullptr;
163 const Node *timestamp_node = nullptr;
164
165 LogType log_type = LogType::kLogMessage;
166
167 // We fill out the metadata at construction, but the actual writers have to
168 // be updated each time we start logging. To avoid duplicating the complex
169 // logic determining whether each writer should be initialized, we just
170 // stash the answer in separate member variables.
171 bool wants_writer = false;
172 DetachedBufferWriter *writer = nullptr;
173 bool wants_timestamp_writer = false;
174 DetachedBufferWriter *timestamp_writer = nullptr;
175 bool wants_contents_writer = false;
176 DetachedBufferWriter *contents_writer = nullptr;
177
178 // Node which this data is from, or -1 if it is unknown.
179 int data_node_index = -1;
180 // Node that this timestamp is for, or -1 if it is known.
181 int timestamp_node_index = -1;
182 // Node that the contents this contents_writer will log are from.
183 int contents_node_index = -1;
184 };
185
186 // Vector mapping from the channel index from the event loop to the logged
187 // channel index.
188 std::vector<int> event_loop_to_logged_channel_index_;
189
190 struct NodeState {
191 aos::monotonic_clock::time_point monotonic_start_time =
192 aos::monotonic_clock::min_time;
193 aos::realtime_clock::time_point realtime_start_time =
194 aos::realtime_clock::min_time;
195
196 bool has_source_node_boot_uuid = false;
197
198 // This is an initial UUID that is a valid UUID4 and is pretty obvious that
199 // it isn't valid.
Austin Schuhcdd90272021-03-15 12:46:16 -0700200 UUID source_node_boot_uuid = UUID::Zero();
Austin Schuhb06f03b2021-02-17 22:00:37 -0800201
202 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> log_file_header =
203 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader>::Empty();
204
205 // True if a header has been written to the start of a log file.
206 bool header_written = false;
207 // True if the current written header represents the contents which will
208 // follow. This is cleared when boot_uuid is known to not match anymore.
209 bool header_valid = false;
210
Austin Schuhcdd90272021-03-15 12:46:16 -0700211 // Sets the source_node_boot_uuid, properly updating everything. Returns
212 // true if it changed, false otherwise.
213 bool SetBootUUID(const UUID &new_source_node_boot_uuid) {
214 if (has_source_node_boot_uuid &&
215 source_node_boot_uuid == new_source_node_boot_uuid) {
216 return false;
217 }
Austin Schuhb06f03b2021-02-17 22:00:37 -0800218 source_node_boot_uuid = new_source_node_boot_uuid;
219 header_valid = false;
220 has_source_node_boot_uuid = true;
221
222 flatbuffers::String *source_node_boot_uuid_string =
223 log_file_header.mutable_message()->mutable_source_node_boot_uuid();
Austin Schuhcdd90272021-03-15 12:46:16 -0700224 CHECK_EQ(UUID::kStringSize, source_node_boot_uuid_string->size());
225 source_node_boot_uuid.CopyTo(source_node_boot_uuid_string->data());
226
227 return true;
Austin Schuhb06f03b2021-02-17 22:00:37 -0800228 }
229 };
230
231 void WriteHeader();
232
233 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> MakeHeader(
234 const Node *node, std::string_view config_sha256);
235
236 // Writes the header for the provided node if enough information is valid.
237 void MaybeWriteHeader(int node_index);
238 // Overload for when we already know node as well.
239 void MaybeWriteHeader(int node_index, const Node *node);
240
241 bool MaybeUpdateTimestamp(
242 const Node *node, int node_index,
243 aos::monotonic_clock::time_point monotonic_start_time,
244 aos::realtime_clock::time_point realtime_start_time);
245
246 void DoLogData(const monotonic_clock::time_point end_time);
247
248 void WriteMissingTimestamps();
249
Austin Schuh855f8932021-03-19 22:01:32 -0700250 // Fetches from each channel until all the data is logged. This is dangerous
251 // because it lets you log for more than 1 period. All calls need to verify
252 // that t isn't greater than 1 period in the future.
Austin Schuhb06f03b2021-02-17 22:00:37 -0800253 void LogUntil(monotonic_clock::time_point t);
254
255 void RecordFetchResult(aos::monotonic_clock::time_point start,
256 aos::monotonic_clock::time_point end, bool got_new,
257 FetcherStruct *fetcher);
258
259 void RecordCreateMessageTime(aos::monotonic_clock::time_point start,
260 aos::monotonic_clock::time_point end,
261 FetcherStruct *fetcher);
262
263 // Sets the start time for a specific node.
264 void SetStartTime(
265 size_t node_index, aos::monotonic_clock::time_point monotonic_start_time,
266 aos::realtime_clock::time_point realtime_start_time,
267 aos::monotonic_clock::time_point logger_monotonic_start_time,
268 aos::realtime_clock::time_point logger_realtime_start_time);
269
270 EventLoop *const event_loop_;
271 // The configuration to place at the top of the log file.
272 const Configuration *const configuration_;
273
274 UUID log_event_uuid_ = UUID::Zero();
275 const UUID logger_instance_uuid_ = UUID::Random();
276 std::unique_ptr<LogNamer> log_namer_;
277 // Empty indicates there isn't one.
278 std::string log_start_uuid_;
279
280 // Name to save in the log file. Defaults to hostname.
281 std::string name_;
282
283 std::function<void()> on_logged_period_ = []() {};
284
285 std::chrono::nanoseconds max_message_fetch_time_ =
286 std::chrono::nanoseconds::zero();
287 int max_message_fetch_time_channel_ = -1;
288 int max_message_fetch_time_size_ = -1;
289 std::chrono::nanoseconds total_message_fetch_time_ =
290 std::chrono::nanoseconds::zero();
291 int total_message_fetch_count_ = 0;
292 int64_t total_message_fetch_bytes_ = 0;
293
294 std::chrono::nanoseconds total_nop_fetch_time_ =
295 std::chrono::nanoseconds::zero();
296 int total_nop_fetch_count_ = 0;
297
298 std::chrono::nanoseconds max_copy_time_ = std::chrono::nanoseconds::zero();
299 int max_copy_time_channel_ = -1;
300 int max_copy_time_size_ = -1;
301 std::chrono::nanoseconds total_copy_time_ = std::chrono::nanoseconds::zero();
302 int total_copy_count_ = 0;
303 int64_t total_copy_bytes_ = 0;
304
305 std::vector<FetcherStruct> fetchers_;
306 TimerHandler *timer_handler_;
307
308 // Period to poll the channels.
309 std::chrono::nanoseconds polling_period_ = std::chrono::milliseconds(100);
310
311 // Last time that data was written for all channels to disk.
312 monotonic_clock::time_point last_synchronized_time_;
313
314 // Max size that the header has consumed. This much extra data will be
315 // reserved in the builder to avoid reallocating.
316 size_t max_header_size_ = 0;
317
318 // If true, write the message header into a separate file.
319 bool separate_config_ = true;
320
321 // Fetcher for all the statistics from all the nodes.
322 aos::Fetcher<message_bridge::ServerStatistics> server_statistics_fetcher_;
323
324 std::vector<NodeState> node_state_;
325};
326
327} // namespace logger
328} // namespace aos
329
330#endif // AOS_EVENTS_LOGGING_LOG_WRITER_H_