blob: 50e9300cf51bbfdcd383acab70391bbfbb828ff2 [file] [log] [blame]
James Kuszmaul4ed5fb12022-03-22 15:20:04 -07001#ifndef AOS_UTIL_MCAP_LOGGER_H_
2#define AOS_UTIL_MCAP_LOGGER_H_
3
4#include "aos/configuration_generated.h"
5#include "aos/events/event_loop.h"
6#include "aos/fast_string_builder.h"
7#include "aos/flatbuffer_utils.h"
8#include "single_include/nlohmann/json.hpp"
9
10namespace aos {
11
12// Produces a JSON Schema (https://json-schema.org/) for a given flatbuffer
13// type. If recursion_level is set, will include a $schema attribute indicating
14// the schema definition being used (this is used to allow for recursion).
15//
16// Note that this is pretty bare-bones, so, e.g., we don't distinguish between
17// structs and tables when generating the JSON schema, so we don't bother to
18// mark struct fields as required.
19enum class JsonSchemaRecursion {
20 kTopLevel,
21 kNested,
22};
23nlohmann::json JsonSchemaForFlatbuffer(
24 const FlatbufferType &type,
25 JsonSchemaRecursion recursion_level = JsonSchemaRecursion::kTopLevel);
26
James Kuszmaul1e418f62023-02-26 14:40:20 -080027// Returns the shortest possible alias for the specified channel on the
28// specified node/application.
29std::string ShortenedChannelName(const aos::Configuration *config,
30 const aos::Channel *channel,
31 std::string_view application_name,
32 const aos::Node *node);
33
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070034// Generates an MCAP file, per the specification at
35// https://github.com/foxglove/mcap/tree/main/docs/specification
James Kuszmaulb3fba252022-04-06 15:13:31 -070036// This currently generates an uncompressed logfile with full message indexing
37// available, to be able to support Foxglove fully.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070038class McapLogger {
39 public:
James Kuszmaulc31d7362022-05-27 14:20:04 -070040 // Whether to serialize the messages into the MCAP file as JSON or
41 // flatbuffers.
42 enum class Serialization {
43 kJson,
44 kFlatbuffer,
45 };
James Kuszmaul9f607c62022-10-27 17:01:55 -070046 // Whether to attempt to shorten channel names.
47 enum class CanonicalChannelNames {
48 // Just use the full, unambiguous, channel names.
49 kCanonical,
50 // Use GetChannelAliases() to determine the shortest possible name for the
51 // channel for the current node, and use that in the MCAP file. This makes
52 // it so that the channels in the resulting file are more likely to match
53 // the channel names that are used in "real" applications.
54 kShortened,
55 };
James Kuszmaul5ab990d2022-11-07 16:35:49 -080056 // Chunk compression to use in the MCAP file.
57 enum class Compression {
58 kNone,
59 kLz4,
60 };
James Kuszmaulc31d7362022-05-27 14:20:04 -070061 McapLogger(EventLoop *event_loop, const std::string &output_path,
James Kuszmaul5ab990d2022-11-07 16:35:49 -080062 Serialization serialization,
63 CanonicalChannelNames canonical_channels, Compression compression);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070064 ~McapLogger();
65
66 private:
67 enum class OpCode {
68 kHeader = 0x01,
69 kFooter = 0x02,
70 kSchema = 0x03,
71 kChannel = 0x04,
72 kMessage = 0x05,
James Kuszmaulb3fba252022-04-06 15:13:31 -070073 kChunk = 0x06,
74 kMessageIndex = 0x07,
75 kChunkIndex = 0x08,
76 kAttachment = 0x09,
77 kAttachmentIndex = 0x0A,
78 kStatistics = 0x0B,
79 kMetadata = 0x0C,
80 kMetadataIndex = 0x0D,
81 kSummaryOffset = 0x0E,
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070082 kDataEnd = 0x0F,
83 };
James Kuszmaulb3fba252022-04-06 15:13:31 -070084 // Stores information associated with a SummaryOffset entry (an offset to the
85 // start of a section within Summary section, which allows readers to quickly
86 // find all the indices/channel definitions/etc. for a given log).
87 struct SummaryOffset {
88 OpCode op_code;
89 // Offset from the start of the file.
90 uint64_t offset;
91 // Total length of the section, in bytes.
92 uint64_t size;
93 };
94 // Information needed to build a ChunkIndex entry.
95 struct ChunkIndex {
96 // Earliest and latest message times within the Chunk being referenced.
97 aos::monotonic_clock::time_point start_time;
98 aos::monotonic_clock::time_point end_time;
99 // Offset from the start of the file to the start of the relevant Chunk.
100 uint64_t offset;
101 // Total size of the Chunk, in bytes.
102 uint64_t chunk_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800103 // Total uncompressed size of the records portion of the Chunk, in bytes.
James Kuszmaulb3fba252022-04-06 15:13:31 -0700104 uint64_t records_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800105 // Total size of the records portion of the Chunk, when compressed
106 uint64_t records_size_compressed;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700107 // Mapping of channel IDs to the MessageIndex entry for that channel within
108 // the referenced Chunk. The MessageIndex is referenced by an offset from
109 // the start of the file.
110 std::map<uint16_t, uint64_t> message_index_offsets;
111 // Total size, in bytes, of all the MessageIndex entries for this Chunk
112 // together (note that they are required to be contiguous).
113 uint64_t message_index_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800114 // Compression used in this Chunk.
115 Compression compression;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700116 };
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800117 // Maintains the state of a single Chunk. In order to maximize read
118 // performance, we currently maintain separate chunks for each channel so
119 // that, in order to read a given channel, only data associated with that
120 // channel nead be read.
James Kuszmaul36a25f42022-10-28 10:18:00 -0700121 struct ChunkStatus {
122 // Buffer containing serialized message data for the currently-being-built
123 // chunk.
124 std::stringstream data;
125 // Earliest message observed in this chunk.
126 std::optional<aos::monotonic_clock::time_point> earliest_message;
127 // Latest message observed in this chunk.
128 std::optional<aos::monotonic_clock::time_point> latest_message;
129 // MessageIndex's for each message. The std::map is indexed by channel ID.
130 // The vector is then a series of pairs of (timestamp, offset from start of
131 // data).
132 // Note that currently this will only ever have one entry, for the channel
133 // that this chunk corresponds to. However, the standard provides for there
134 // being more than one channel per chunk and so we still have some code that
135 // supports that.
136 std::map<uint16_t, std::vector<std::pair<uint64_t, uint64_t>>>
137 message_indices;
138 };
James Kuszmaulb3fba252022-04-06 15:13:31 -0700139 enum class RegisterHandlers { kYes, kNo };
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700140 // Helpers to write each type of relevant record.
141 void WriteMagic();
142 void WriteHeader();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700143 void WriteFooter(uint64_t summary_offset, uint64_t summary_offset_offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700144 void WriteDataEnd();
145 void WriteSchema(const uint16_t id, const aos::Channel *channel);
146 void WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700147 const aos::Channel *channel,
148 std::string_view override_name = "");
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700149 void WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700150 const Context &context, ChunkStatus *chunk);
151 void WriteChunk(ChunkStatus *chunk);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700152
James Kuszmaulbed2af02023-01-28 15:57:24 -0800153 // Writes out the special configuration channel. This gets called right before
154 // the first actual message is written so that we can have a reasonable
155 // monotonic clock time.
156 void WriteConfigurationMessage();
157
James Kuszmaulb3fba252022-04-06 15:13:31 -0700158 // The helpers for writing records which appear in the Summary section will
159 // return SummaryOffset's so that they can be referenced in the SummaryOffset
160 // section.
161 SummaryOffset WriteChunkIndices();
162 SummaryOffset WriteStatistics();
163 std::vector<SummaryOffset> WriteSchemasAndChannels(
164 RegisterHandlers register_handlers);
165 void WriteSummaryOffset(const SummaryOffset &offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700166
167 // Writes an MCAP record to the output file.
James Kuszmaulb3fba252022-04-06 15:13:31 -0700168 void WriteRecord(OpCode op, std::string_view record, std::ostream *ostream);
169 void WriteRecord(OpCode op, std::string_view record) {
170 WriteRecord(op, record, &output_);
171 }
172 // Adds an MCAP-spec string/byte-array/map/array of pairs/fixed-size integer
173 // to a buffer.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700174 static void AppendString(FastStringBuilder *builder, std::string_view string);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700175 static void AppendBytes(FastStringBuilder *builder, std::string_view bytes);
176 static void AppendChannelMap(FastStringBuilder *builder,
177 const std::map<uint16_t, uint64_t> &map);
178 static void AppendMessageIndices(
179 FastStringBuilder *builder,
180 const std::vector<std::pair<uint64_t, uint64_t>> &messages);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700181 static void AppendInt16(FastStringBuilder *builder, uint16_t val);
182 static void AppendInt32(FastStringBuilder *builder, uint32_t val);
183 static void AppendInt64(FastStringBuilder *builder, uint64_t val);
184
James Kuszmaulb3fba252022-04-06 15:13:31 -0700185 aos::EventLoop *event_loop_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700186 std::ofstream output_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700187 const Serialization serialization_;
James Kuszmaul9f607c62022-10-27 17:01:55 -0700188 const CanonicalChannelNames canonical_channels_;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800189 const Compression compression_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700190 size_t total_message_bytes_ = 0;
191 std::map<const Channel *, size_t> total_channel_bytes_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700192 FastStringBuilder string_builder_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700193
194 // Earliest message observed in this logfile.
195 std::optional<aos::monotonic_clock::time_point> earliest_message_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700196 // Latest message observed in this logfile.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800197 aos::monotonic_clock::time_point latest_message_ =
198 aos::monotonic_clock::min_time;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700199 // Count of all messages on each channel, indexed by channel ID.
200 std::map<uint16_t, uint64_t> message_counts_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700201 std::map<uint16_t, std::unique_ptr<RawFetcher>> fetchers_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700202 // All currently-being-built chunks. Indexed by channel ID. This is used to
203 // segregate channels into separate chunks to support more efficient reading.
204 std::map<uint16_t, ChunkStatus> current_chunks_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700205 // ChunkIndex's for all fully written Chunks.
206 std::vector<ChunkIndex> chunk_indices_;
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700207
208 // Metadata associated with the fake "configuration" channel that we create in
209 // order to ensure that foxglove extensions/users have access to the full
210 // configuration.
211 uint16_t configuration_id_ = 0;
212 FlatbufferDetachedBuffer<Channel> configuration_channel_;
213 FlatbufferDetachedBuffer<Configuration> configuration_;
James Kuszmaulbed2af02023-01-28 15:57:24 -0800214 bool wrote_configuration_ = false;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800215
216 // Memory buffer to use for compressing data.
217 std::vector<uint8_t> compression_buffer_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700218};
219} // namespace aos
220#endif // AOS_UTIL_MCAP_LOGGER_H_