blob: 8032c76384a4a5eb466d1becea6c00ec6fa926f4 [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
Philipp Schrader790cb542023-07-05 21:06:52 -07004#include "single_include/nlohmann/json.hpp"
5
James Kuszmaul4ed5fb12022-03-22 15:20:04 -07006#include "aos/configuration_generated.h"
7#include "aos/events/event_loop.h"
8#include "aos/fast_string_builder.h"
9#include "aos/flatbuffer_utils.h"
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070010
11namespace aos {
12
13// Produces a JSON Schema (https://json-schema.org/) for a given flatbuffer
14// type. If recursion_level is set, will include a $schema attribute indicating
15// the schema definition being used (this is used to allow for recursion).
16//
17// Note that this is pretty bare-bones, so, e.g., we don't distinguish between
18// structs and tables when generating the JSON schema, so we don't bother to
19// mark struct fields as required.
20enum class JsonSchemaRecursion {
21 kTopLevel,
22 kNested,
23};
24nlohmann::json JsonSchemaForFlatbuffer(
25 const FlatbufferType &type,
26 JsonSchemaRecursion recursion_level = JsonSchemaRecursion::kTopLevel);
27
James Kuszmaul1e418f62023-02-26 14:40:20 -080028// Returns the shortest possible alias for the specified channel on the
29// specified node/application.
30std::string ShortenedChannelName(const aos::Configuration *config,
31 const aos::Channel *channel,
32 std::string_view application_name,
33 const aos::Node *node);
34
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070035// Generates an MCAP file, per the specification at
36// https://github.com/foxglove/mcap/tree/main/docs/specification
James Kuszmaulb3fba252022-04-06 15:13:31 -070037// This currently generates an uncompressed logfile with full message indexing
38// available, to be able to support Foxglove fully.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070039class McapLogger {
40 public:
James Kuszmaulc31d7362022-05-27 14:20:04 -070041 // Whether to serialize the messages into the MCAP file as JSON or
42 // flatbuffers.
43 enum class Serialization {
44 kJson,
45 kFlatbuffer,
46 };
James Kuszmaul9f607c62022-10-27 17:01:55 -070047 // Whether to attempt to shorten channel names.
48 enum class CanonicalChannelNames {
49 // Just use the full, unambiguous, channel names.
50 kCanonical,
51 // Use GetChannelAliases() to determine the shortest possible name for the
52 // channel for the current node, and use that in the MCAP file. This makes
53 // it so that the channels in the resulting file are more likely to match
54 // the channel names that are used in "real" applications.
55 kShortened,
56 };
James Kuszmaul5ab990d2022-11-07 16:35:49 -080057 // Chunk compression to use in the MCAP file.
58 enum class Compression {
59 kNone,
60 kLz4,
61 };
James Kuszmaulc31d7362022-05-27 14:20:04 -070062 McapLogger(EventLoop *event_loop, const std::string &output_path,
James Kuszmaul5ab990d2022-11-07 16:35:49 -080063 Serialization serialization,
64 CanonicalChannelNames canonical_channels, Compression compression);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070065 ~McapLogger();
66
67 private:
68 enum class OpCode {
69 kHeader = 0x01,
70 kFooter = 0x02,
71 kSchema = 0x03,
72 kChannel = 0x04,
73 kMessage = 0x05,
James Kuszmaulb3fba252022-04-06 15:13:31 -070074 kChunk = 0x06,
75 kMessageIndex = 0x07,
76 kChunkIndex = 0x08,
77 kAttachment = 0x09,
78 kAttachmentIndex = 0x0A,
79 kStatistics = 0x0B,
80 kMetadata = 0x0C,
81 kMetadataIndex = 0x0D,
82 kSummaryOffset = 0x0E,
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070083 kDataEnd = 0x0F,
84 };
James Kuszmaulb3fba252022-04-06 15:13:31 -070085 // Stores information associated with a SummaryOffset entry (an offset to the
86 // start of a section within Summary section, which allows readers to quickly
87 // find all the indices/channel definitions/etc. for a given log).
88 struct SummaryOffset {
89 OpCode op_code;
90 // Offset from the start of the file.
91 uint64_t offset;
92 // Total length of the section, in bytes.
93 uint64_t size;
94 };
95 // Information needed to build a ChunkIndex entry.
96 struct ChunkIndex {
97 // Earliest and latest message times within the Chunk being referenced.
98 aos::monotonic_clock::time_point start_time;
99 aos::monotonic_clock::time_point end_time;
100 // Offset from the start of the file to the start of the relevant Chunk.
101 uint64_t offset;
102 // Total size of the Chunk, in bytes.
103 uint64_t chunk_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800104 // Total uncompressed size of the records portion of the Chunk, in bytes.
James Kuszmaulb3fba252022-04-06 15:13:31 -0700105 uint64_t records_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800106 // Total size of the records portion of the Chunk, when compressed
107 uint64_t records_size_compressed;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700108 // Mapping of channel IDs to the MessageIndex entry for that channel within
109 // the referenced Chunk. The MessageIndex is referenced by an offset from
110 // the start of the file.
111 std::map<uint16_t, uint64_t> message_index_offsets;
112 // Total size, in bytes, of all the MessageIndex entries for this Chunk
113 // together (note that they are required to be contiguous).
114 uint64_t message_index_size;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800115 // Compression used in this Chunk.
116 Compression compression;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700117 };
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800118 // Maintains the state of a single Chunk. In order to maximize read
119 // performance, we currently maintain separate chunks for each channel so
120 // that, in order to read a given channel, only data associated with that
121 // channel nead be read.
James Kuszmaul36a25f42022-10-28 10:18:00 -0700122 struct ChunkStatus {
123 // Buffer containing serialized message data for the currently-being-built
124 // chunk.
125 std::stringstream data;
126 // Earliest message observed in this chunk.
127 std::optional<aos::monotonic_clock::time_point> earliest_message;
128 // Latest message observed in this chunk.
129 std::optional<aos::monotonic_clock::time_point> latest_message;
130 // MessageIndex's for each message. The std::map is indexed by channel ID.
131 // The vector is then a series of pairs of (timestamp, offset from start of
132 // data).
133 // Note that currently this will only ever have one entry, for the channel
134 // that this chunk corresponds to. However, the standard provides for there
135 // being more than one channel per chunk and so we still have some code that
136 // supports that.
137 std::map<uint16_t, std::vector<std::pair<uint64_t, uint64_t>>>
138 message_indices;
139 };
James Kuszmaulb3fba252022-04-06 15:13:31 -0700140 enum class RegisterHandlers { kYes, kNo };
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700141 // Helpers to write each type of relevant record.
142 void WriteMagic();
143 void WriteHeader();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700144 void WriteFooter(uint64_t summary_offset, uint64_t summary_offset_offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700145 void WriteDataEnd();
146 void WriteSchema(const uint16_t id, const aos::Channel *channel);
147 void WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700148 const aos::Channel *channel,
149 std::string_view override_name = "");
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700150 void WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700151 const Context &context, ChunkStatus *chunk);
152 void WriteChunk(ChunkStatus *chunk);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700153
James Kuszmaulbed2af02023-01-28 15:57:24 -0800154 // Writes out the special configuration channel. This gets called right before
155 // the first actual message is written so that we can have a reasonable
156 // monotonic clock time.
157 void WriteConfigurationMessage();
158
James Kuszmaulb3fba252022-04-06 15:13:31 -0700159 // The helpers for writing records which appear in the Summary section will
160 // return SummaryOffset's so that they can be referenced in the SummaryOffset
161 // section.
162 SummaryOffset WriteChunkIndices();
163 SummaryOffset WriteStatistics();
164 std::vector<SummaryOffset> WriteSchemasAndChannels(
165 RegisterHandlers register_handlers);
166 void WriteSummaryOffset(const SummaryOffset &offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700167
168 // Writes an MCAP record to the output file.
James Kuszmaulb3fba252022-04-06 15:13:31 -0700169 void WriteRecord(OpCode op, std::string_view record, std::ostream *ostream);
170 void WriteRecord(OpCode op, std::string_view record) {
171 WriteRecord(op, record, &output_);
172 }
173 // Adds an MCAP-spec string/byte-array/map/array of pairs/fixed-size integer
174 // to a buffer.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700175 static void AppendString(FastStringBuilder *builder, std::string_view string);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700176 static void AppendBytes(FastStringBuilder *builder, std::string_view bytes);
177 static void AppendChannelMap(FastStringBuilder *builder,
178 const std::map<uint16_t, uint64_t> &map);
179 static void AppendMessageIndices(
180 FastStringBuilder *builder,
181 const std::vector<std::pair<uint64_t, uint64_t>> &messages);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700182 static void AppendInt16(FastStringBuilder *builder, uint16_t val);
183 static void AppendInt32(FastStringBuilder *builder, uint32_t val);
184 static void AppendInt64(FastStringBuilder *builder, uint64_t val);
185
James Kuszmaulb3fba252022-04-06 15:13:31 -0700186 aos::EventLoop *event_loop_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700187 std::ofstream output_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700188 const Serialization serialization_;
James Kuszmaul9f607c62022-10-27 17:01:55 -0700189 const CanonicalChannelNames canonical_channels_;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800190 const Compression compression_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700191 size_t total_message_bytes_ = 0;
192 std::map<const Channel *, size_t> total_channel_bytes_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700193 FastStringBuilder string_builder_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700194
195 // Earliest message observed in this logfile.
196 std::optional<aos::monotonic_clock::time_point> earliest_message_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700197 // Latest message observed in this logfile.
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800198 aos::monotonic_clock::time_point latest_message_ =
199 aos::monotonic_clock::min_time;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700200 // Count of all messages on each channel, indexed by channel ID.
201 std::map<uint16_t, uint64_t> message_counts_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700202 std::map<uint16_t, std::unique_ptr<RawFetcher>> fetchers_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700203 // All currently-being-built chunks. Indexed by channel ID. This is used to
204 // segregate channels into separate chunks to support more efficient reading.
205 std::map<uint16_t, ChunkStatus> current_chunks_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700206 // ChunkIndex's for all fully written Chunks.
207 std::vector<ChunkIndex> chunk_indices_;
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700208
209 // Metadata associated with the fake "configuration" channel that we create in
210 // order to ensure that foxglove extensions/users have access to the full
211 // configuration.
212 uint16_t configuration_id_ = 0;
213 FlatbufferDetachedBuffer<Channel> configuration_channel_;
214 FlatbufferDetachedBuffer<Configuration> configuration_;
James Kuszmaulbed2af02023-01-28 15:57:24 -0800215 bool wrote_configuration_ = false;
James Kuszmaul5ab990d2022-11-07 16:35:49 -0800216
217 // Memory buffer to use for compressing data.
218 std::vector<uint8_t> compression_buffer_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700219};
220} // namespace aos
221#endif // AOS_UTIL_MCAP_LOGGER_H_