blob: 7e581527b097f3a50bc6760ef0bc022c206a0c7d [file] [log] [blame]
Austin Schuhcb5601b2020-09-10 15:29:59 -07001#ifndef AOS_EVENTS_LOGGING_LOG_NAMER_H_
2#define AOS_EVENTS_LOGGING_LOG_NAMER_H_
3
4#include <functional>
5#include <map>
6#include <memory>
7#include <string_view>
8#include <vector>
9
10#include "aos/events/logging/logfile_utils.h"
11#include "aos/events/logging/logger_generated.h"
12#include "aos/events/logging/uuid.h"
13#include "flatbuffers/flatbuffers.h"
14
15namespace aos {
16namespace logger {
17
18// Interface describing how to name, track, and add headers to log file parts.
19class LogNamer {
20 public:
21 // Constructs a LogNamer with the primary node (ie the one the logger runs on)
22 // being node.
23 LogNamer(const Node *node) : node_(node) { nodes_.emplace_back(node_); }
24 virtual ~LogNamer() {}
25
26 // Writes the header to all log files for a specific node. This function
27 // needs to be called after all the writers are created.
28 //
29 // Modifies header to contain the uuid and part number for each writer as it
30 // writes it. Since this is done unconditionally, it does not restore the
31 // previous value at the end.
32 virtual void WriteHeader(
33 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header,
34 const Node *node) = 0;
35
Brian Silverman87ac0402020-09-17 14:47:01 -070036 // Returns a writer for writing data from messages on this channel (on the
37 // primary node).
38 //
39 // The returned pointer will stay valid across rotations, but the object it
40 // points to will be assigned to.
Austin Schuhcb5601b2020-09-10 15:29:59 -070041 virtual DetachedBufferWriter *MakeWriter(const Channel *channel) = 0;
42
Brian Silverman87ac0402020-09-17 14:47:01 -070043 // Returns a writer for writing timestamps from messages on this channel (on
44 // the primary node).
45 //
46 // The returned pointer will stay valid across rotations, but the object it
47 // points to will be assigned to.
Austin Schuhcb5601b2020-09-10 15:29:59 -070048 virtual DetachedBufferWriter *MakeTimestampWriter(const Channel *channel) = 0;
49
50 // Returns a writer for writing timestamps delivered over the special
51 // /aos/remote_timestamps/* channels. node is the node that the timestamps
Brian Silverman87ac0402020-09-17 14:47:01 -070052 // are forwarded back from (to the primary node).
53 //
54 // The returned pointer will stay valid across rotations, but the object it
55 // points to will be assigned to.
Austin Schuhcb5601b2020-09-10 15:29:59 -070056 virtual DetachedBufferWriter *MakeForwardedTimestampWriter(
57 const Channel *channel, const Node *node) = 0;
58
59 // Rotates all log files for the provided node. The provided header will be
60 // modified and written per WriteHeader above.
61 virtual void Rotate(
62 const Node *node,
63 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header) = 0;
64
Austin Schuh315b96b2020-12-11 21:21:12 -080065 // Reboots all log files for the provided node. The provided header will be
66 // modified and written per WriteHeader above. Resets any parts UUIDs.
67 virtual void Reboot(
68 const Node *node,
69 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header) = 0;
70
Austin Schuhcb5601b2020-09-10 15:29:59 -070071 // Returns all the nodes that data is being written for.
72 const std::vector<const Node *> &nodes() const { return nodes_; }
73
74 // Returns the node the logger is running on.
75 const Node *node() const { return node_; }
76
77 protected:
78 // Modifies the header to have the provided UUID and part id.
79 void UpdateHeader(
80 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header,
81 const UUID &uuid, int part_id) const;
82
83 const Node *const node_;
84 std::vector<const Node *> nodes_;
85};
86
87// Local log namer is a simple version which only names things
88// "base_name.part#.bfbs" and increments the part number. It doesn't support
89// any other log type.
90class LocalLogNamer : public LogNamer {
91 public:
92 LocalLogNamer(std::string_view base_name, const Node *node)
93 : LogNamer(node),
94 base_name_(base_name),
95 uuid_(UUID::Random()),
96 data_writer_(OpenDataWriter()) {}
Brian Silverman0465fcf2020-09-24 00:29:18 -070097 ~LocalLogNamer() override = default;
Austin Schuhcb5601b2020-09-10 15:29:59 -070098
99 void WriteHeader(
100 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header,
101 const Node *node) override;
102
103 DetachedBufferWriter *MakeWriter(const Channel *channel) override;
104
105 void Rotate(const Node *node,
106 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header)
107 override;
108
Austin Schuh315b96b2020-12-11 21:21:12 -0800109 void Reboot(const Node *node,
110 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header)
111 override;
112
Austin Schuhcb5601b2020-09-10 15:29:59 -0700113 DetachedBufferWriter *MakeTimestampWriter(const Channel *channel) override;
114
115 DetachedBufferWriter *MakeForwardedTimestampWriter(
116 const Channel * /*channel*/, const Node * /*node*/) override;
117
118 private:
119 // Creates a new data writer with the new part number.
120 std::unique_ptr<DetachedBufferWriter> OpenDataWriter() {
121 return std::make_unique<DetachedBufferWriter>(
Brian Silvermanf51499a2020-09-21 12:49:08 -0700122 absl::StrCat(base_name_, ".part", part_number_, ".bfbs"),
123 std::make_unique<aos::logger::DummyEncoder>());
Austin Schuhcb5601b2020-09-10 15:29:59 -0700124 }
125
126 const std::string base_name_;
127 const UUID uuid_;
128 size_t part_number_ = 0;
129 std::unique_ptr<DetachedBufferWriter> data_writer_;
130};
131
132// Log namer which uses a config and a base name to name a bunch of files.
133class MultiNodeLogNamer : public LogNamer {
134 public:
Brian Silvermancb805822020-10-06 17:43:35 -0700135 MultiNodeLogNamer(std::string_view base_name,
136 const Configuration *configuration, const Node *node);
137 ~MultiNodeLogNamer() override;
138
139 std::string_view base_name() const { return base_name_; }
140
Brian Silverman48deab12020-09-30 18:39:28 -0700141 // If temp_suffix is set, then this will write files under names beginning
142 // with the specified suffix, and then rename them to the desired name after
143 // they are fully written.
144 //
145 // This is useful to enable incremental copying of the log files.
146 //
147 // Defaults to writing directly to the final filename.
Brian Silvermancb805822020-10-06 17:43:35 -0700148 void set_temp_suffix(std::string_view temp_suffix) {
149 temp_suffix_ = temp_suffix;
150 }
Austin Schuhcb5601b2020-09-10 15:29:59 -0700151
Brian Silvermancb805822020-10-06 17:43:35 -0700152 // Sets the function for creating encoders.
153 //
154 // Defaults to just creating DummyEncoders.
155 void set_encoder_factory(
156 std::function<std::unique_ptr<DetachedBufferEncoder>()> encoder_factory) {
157 encoder_factory_ = std::move(encoder_factory);
158 }
159
160 // Sets an additional file extension.
161 //
162 // Defaults to nothing.
163 void set_extension(std::string_view extension) { extension_ = extension; }
Brian Silverman1f345222020-09-24 21:14:48 -0700164
Brian Silvermana621f522020-09-30 16:52:43 -0700165 // A list of all the filenames we've written.
166 //
167 // This only includes the part after base_name().
168 const std::vector<std::string> &all_filenames() const {
169 return all_filenames_;
170 }
171
Austin Schuhcb5601b2020-09-10 15:29:59 -0700172 void WriteHeader(
173 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header,
174 const Node *node) override;
175
176 void Rotate(const Node *node,
177 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header)
178 override;
179
Austin Schuh315b96b2020-12-11 21:21:12 -0800180 void Reboot(const Node *node,
181 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header)
182 override;
183
Austin Schuhcb5601b2020-09-10 15:29:59 -0700184 DetachedBufferWriter *MakeWriter(const Channel *channel) override;
185
Brian Silvermand90905f2020-09-23 14:42:56 -0700186 DetachedBufferWriter *MakeForwardedTimestampWriter(const Channel *channel,
187 const Node *node) override;
Austin Schuhcb5601b2020-09-10 15:29:59 -0700188
189 DetachedBufferWriter *MakeTimestampWriter(const Channel *channel) override;
190
Brian Silverman0465fcf2020-09-24 00:29:18 -0700191 // Indicates that at least one file ran out of space. Once this happens, we
192 // stop trying to open new files, to avoid writing any files with holes from
193 // previous parts.
194 //
195 // Besides this function, this object will silently stop logging data when
196 // this occurs. If you want to ensure log files are complete, you must call
197 // this method.
Brian Silvermana9f2ec92020-10-06 18:00:53 -0700198 bool ran_out_of_space() const {
199 return accumulate_data_writers<bool>(
200 ran_out_of_space_, [](bool x, const DataWriter &data_writer) {
201 return x ||
202 (data_writer.writer && data_writer.writer->ran_out_of_space());
203 });
204 }
Brian Silverman0465fcf2020-09-24 00:29:18 -0700205
Brian Silverman1f345222020-09-24 21:14:48 -0700206 // Returns the maximum total_bytes() value for all existing
207 // DetachedBufferWriters.
208 //
209 // Returns 0 if no files are open.
210 size_t maximum_total_bytes() const {
Brian Silvermancb805822020-10-06 17:43:35 -0700211 return accumulate_data_writers<size_t>(
212 0, [](size_t x, const DataWriter &data_writer) {
213 return std::max(x, data_writer.writer->total_bytes());
214 });
Brian Silverman1f345222020-09-24 21:14:48 -0700215 }
216
Brian Silverman0465fcf2020-09-24 00:29:18 -0700217 // Closes all existing log files. No more data may be written after this.
218 //
219 // This may set ran_out_of_space().
220 void Close();
221
Brian Silvermancb805822020-10-06 17:43:35 -0700222 // Accessors for various statistics. See the identically-named methods in
223 // DetachedBufferWriter for documentation. These are aggregated across all
224 // past and present DetachedBufferWriters.
225 std::chrono::nanoseconds max_write_time() const {
226 return accumulate_data_writers(
227 max_write_time_,
228 [](std::chrono::nanoseconds x, const DataWriter &data_writer) {
229 return std::max(x, data_writer.writer->max_write_time());
230 });
231 }
232 int max_write_time_bytes() const {
233 return std::get<0>(accumulate_data_writers(
234 std::make_tuple(max_write_time_bytes_, max_write_time_),
235 [](std::tuple<int, std::chrono::nanoseconds> x,
236 const DataWriter &data_writer) {
237 if (data_writer.writer->max_write_time() > std::get<1>(x)) {
238 return std::make_tuple(data_writer.writer->max_write_time_bytes(),
239 data_writer.writer->max_write_time());
240 }
241 return x;
242 }));
243 }
244 int max_write_time_messages() const {
245 return std::get<0>(accumulate_data_writers(
246 std::make_tuple(max_write_time_messages_, max_write_time_),
247 [](std::tuple<int, std::chrono::nanoseconds> x,
248 const DataWriter &data_writer) {
249 if (data_writer.writer->max_write_time() > std::get<1>(x)) {
250 return std::make_tuple(
251 data_writer.writer->max_write_time_messages(),
252 data_writer.writer->max_write_time());
253 }
254 return x;
255 }));
256 }
257 std::chrono::nanoseconds total_write_time() const {
258 return accumulate_data_writers(
259 total_write_time_,
260 [](std::chrono::nanoseconds x, const DataWriter &data_writer) {
261 return x + data_writer.writer->total_write_time();
262 });
263 }
264 int total_write_count() const {
265 return accumulate_data_writers(
266 total_write_count_, [](int x, const DataWriter &data_writer) {
267 return x + data_writer.writer->total_write_count();
268 });
269 }
270 int total_write_messages() const {
271 return accumulate_data_writers(
272 total_write_messages_, [](int x, const DataWriter &data_writer) {
273 return x + data_writer.writer->total_write_messages();
274 });
275 }
276 int total_write_bytes() const {
277 return accumulate_data_writers(
278 total_write_bytes_, [](int x, const DataWriter &data_writer) {
279 return x + data_writer.writer->total_write_bytes();
280 });
281 }
282
283 void ResetStatistics();
284
Austin Schuhcb5601b2020-09-10 15:29:59 -0700285 private:
286 // Files to write remote data to. We want one per channel. Maps the channel
287 // to the writer, Node, and part number.
288 struct DataWriter {
289 std::unique_ptr<DetachedBufferWriter> writer = nullptr;
290 const Node *node;
291 size_t part_number = 0;
Austin Schuh315b96b2020-12-11 21:21:12 -0800292 UUID uuid = UUID::Random();
Austin Schuhcb5601b2020-09-10 15:29:59 -0700293 std::function<void(const Channel *, DataWriter *)> rotate;
294 };
295
Austin Schuh315b96b2020-12-11 21:21:12 -0800296 // Implements Rotate and Reboot, controlled by the 'reboot' flag. The only
297 // difference between the two is if DataWriter::uuid is reset or not.
298 void DoRotate(
299 const Node *node,
300 aos::SizePrefixedFlatbufferDetachedBuffer<LogFileHeader> *header,
301 bool reboot);
302
Austin Schuhcb5601b2020-09-10 15:29:59 -0700303 // Opens up a writer for timestamps forwarded back.
304 void OpenForwardedTimestampWriter(const Channel *channel,
305 DataWriter *data_writer);
306
307 // Opens up a writer for remote data.
308 void OpenWriter(const Channel *channel, DataWriter *data_writer);
309
310 // Opens the main data writer file for this node responsible for data_writer_.
Brian Silvermana621f522020-09-30 16:52:43 -0700311 void OpenDataWriter();
Austin Schuhcb5601b2020-09-10 15:29:59 -0700312
Brian Silvermana621f522020-09-30 16:52:43 -0700313 void CreateBufferWriter(std::string_view path,
Brian Silverman0465fcf2020-09-24 00:29:18 -0700314 std::unique_ptr<DetachedBufferWriter> *destination);
315
Brian Silverman48deab12020-09-30 18:39:28 -0700316 void RenameTempFile(DetachedBufferWriter *destination);
317
Brian Silvermancb805822020-10-06 17:43:35 -0700318 void CloseWriter(std::unique_ptr<DetachedBufferWriter> *writer_pointer);
Austin Schuhcb5601b2020-09-10 15:29:59 -0700319
Brian Silvermancb805822020-10-06 17:43:35 -0700320 // A version of std::accumulate which operates over all of our DataWriters.
321 template <typename T, typename BinaryOperation>
322 T accumulate_data_writers(T t, BinaryOperation op) const {
323 for (const std::pair<const Channel *const, DataWriter> &data_writer :
324 data_writers_) {
Austin Schuhad0cfc32020-12-21 12:34:26 -0800325 if (!data_writer.second.writer) continue;
Brian Silvermancb805822020-10-06 17:43:35 -0700326 t = op(std::move(t), data_writer.second);
327 }
328 if (data_writer_.writer) {
329 t = op(std::move(t), data_writer_);
330 }
331 return t;
332 }
333
334 const std::string base_name_;
335 const Configuration *const configuration_;
Austin Schuhcb5601b2020-09-10 15:29:59 -0700336
Brian Silverman0465fcf2020-09-24 00:29:18 -0700337 bool ran_out_of_space_ = false;
Brian Silvermana621f522020-09-30 16:52:43 -0700338 std::vector<std::string> all_filenames_;
Brian Silverman0465fcf2020-09-24 00:29:18 -0700339
Brian Silvermancb805822020-10-06 17:43:35 -0700340 std::string temp_suffix_;
341 std::function<std::unique_ptr<DetachedBufferEncoder>()> encoder_factory_ =
342 []() { return std::make_unique<DummyEncoder>(); };
343 std::string extension_;
344
345 // Storage for statistics from previously-rotated DetachedBufferWriters.
346 std::chrono::nanoseconds max_write_time_ = std::chrono::nanoseconds::zero();
347 int max_write_time_bytes_ = -1;
348 int max_write_time_messages_ = -1;
349 std::chrono::nanoseconds total_write_time_ = std::chrono::nanoseconds::zero();
350 int total_write_count_ = 0;
351 int total_write_messages_ = 0;
352 int total_write_bytes_ = 0;
353
Austin Schuhcb5601b2020-09-10 15:29:59 -0700354 // File to write both delivery timestamps and local data to.
Brian Silvermancb805822020-10-06 17:43:35 -0700355 DataWriter data_writer_;
Austin Schuhcb5601b2020-09-10 15:29:59 -0700356
357 std::map<const Channel *, DataWriter> data_writers_;
358};
359
360} // namespace logger
361} // namespace aos
362
363#endif // AOS_EVENTS_LOGGING_LOG_NAMER_H_