blob: 267364a375db4d0495df92624ab1e95d5b963d63 [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
27// Generates an MCAP file, per the specification at
28// https://github.com/foxglove/mcap/tree/main/docs/specification
James Kuszmaulb3fba252022-04-06 15:13:31 -070029// This currently generates an uncompressed logfile with full message indexing
30// available, to be able to support Foxglove fully.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070031class McapLogger {
32 public:
James Kuszmaulc31d7362022-05-27 14:20:04 -070033 // Whether to serialize the messages into the MCAP file as JSON or
34 // flatbuffers.
35 enum class Serialization {
36 kJson,
37 kFlatbuffer,
38 };
James Kuszmaul9f607c62022-10-27 17:01:55 -070039 // Whether to attempt to shorten channel names.
40 enum class CanonicalChannelNames {
41 // Just use the full, unambiguous, channel names.
42 kCanonical,
43 // Use GetChannelAliases() to determine the shortest possible name for the
44 // channel for the current node, and use that in the MCAP file. This makes
45 // it so that the channels in the resulting file are more likely to match
46 // the channel names that are used in "real" applications.
47 kShortened,
48 };
James Kuszmaulc31d7362022-05-27 14:20:04 -070049 McapLogger(EventLoop *event_loop, const std::string &output_path,
James Kuszmaul9f607c62022-10-27 17:01:55 -070050 Serialization serialization, CanonicalChannelNames canonical_channels);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070051 ~McapLogger();
52
53 private:
54 enum class OpCode {
55 kHeader = 0x01,
56 kFooter = 0x02,
57 kSchema = 0x03,
58 kChannel = 0x04,
59 kMessage = 0x05,
James Kuszmaulb3fba252022-04-06 15:13:31 -070060 kChunk = 0x06,
61 kMessageIndex = 0x07,
62 kChunkIndex = 0x08,
63 kAttachment = 0x09,
64 kAttachmentIndex = 0x0A,
65 kStatistics = 0x0B,
66 kMetadata = 0x0C,
67 kMetadataIndex = 0x0D,
68 kSummaryOffset = 0x0E,
James Kuszmaul4ed5fb12022-03-22 15:20:04 -070069 kDataEnd = 0x0F,
70 };
James Kuszmaulb3fba252022-04-06 15:13:31 -070071 // Stores information associated with a SummaryOffset entry (an offset to the
72 // start of a section within Summary section, which allows readers to quickly
73 // find all the indices/channel definitions/etc. for a given log).
74 struct SummaryOffset {
75 OpCode op_code;
76 // Offset from the start of the file.
77 uint64_t offset;
78 // Total length of the section, in bytes.
79 uint64_t size;
80 };
81 // Information needed to build a ChunkIndex entry.
82 struct ChunkIndex {
83 // Earliest and latest message times within the Chunk being referenced.
84 aos::monotonic_clock::time_point start_time;
85 aos::monotonic_clock::time_point end_time;
86 // Offset from the start of the file to the start of the relevant Chunk.
87 uint64_t offset;
88 // Total size of the Chunk, in bytes.
89 uint64_t chunk_size;
90 // Total size of the records portion of the Chunk, in bytes.
91 uint64_t records_size;
92 // Mapping of channel IDs to the MessageIndex entry for that channel within
93 // the referenced Chunk. The MessageIndex is referenced by an offset from
94 // the start of the file.
95 std::map<uint16_t, uint64_t> message_index_offsets;
96 // Total size, in bytes, of all the MessageIndex entries for this Chunk
97 // together (note that they are required to be contiguous).
98 uint64_t message_index_size;
99 };
James Kuszmaul36a25f42022-10-28 10:18:00 -0700100 // Maintains the state of a single Chunk. In order to maximize read performance,
101 // we currently maintain separate chunks for each channel so that, in order to
102 // read a given channel, only data associated with that channel nead be read.
103 struct ChunkStatus {
104 // Buffer containing serialized message data for the currently-being-built
105 // chunk.
106 std::stringstream data;
107 // Earliest message observed in this chunk.
108 std::optional<aos::monotonic_clock::time_point> earliest_message;
109 // Latest message observed in this chunk.
110 std::optional<aos::monotonic_clock::time_point> latest_message;
111 // MessageIndex's for each message. The std::map is indexed by channel ID.
112 // The vector is then a series of pairs of (timestamp, offset from start of
113 // data).
114 // Note that currently this will only ever have one entry, for the channel
115 // that this chunk corresponds to. However, the standard provides for there
116 // being more than one channel per chunk and so we still have some code that
117 // supports that.
118 std::map<uint16_t, std::vector<std::pair<uint64_t, uint64_t>>>
119 message_indices;
120 };
James Kuszmaulb3fba252022-04-06 15:13:31 -0700121 enum class RegisterHandlers { kYes, kNo };
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700122 // Helpers to write each type of relevant record.
123 void WriteMagic();
124 void WriteHeader();
James Kuszmaulb3fba252022-04-06 15:13:31 -0700125 void WriteFooter(uint64_t summary_offset, uint64_t summary_offset_offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700126 void WriteDataEnd();
127 void WriteSchema(const uint16_t id, const aos::Channel *channel);
128 void WriteChannel(const uint16_t id, const uint16_t schema_id,
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700129 const aos::Channel *channel,
130 std::string_view override_name = "");
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700131 void WriteMessage(uint16_t channel_id, const Channel *channel,
James Kuszmaul36a25f42022-10-28 10:18:00 -0700132 const Context &context, ChunkStatus *chunk);
133 void WriteChunk(ChunkStatus *chunk);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700134
135 // The helpers for writing records which appear in the Summary section will
136 // return SummaryOffset's so that they can be referenced in the SummaryOffset
137 // section.
138 SummaryOffset WriteChunkIndices();
139 SummaryOffset WriteStatistics();
140 std::vector<SummaryOffset> WriteSchemasAndChannels(
141 RegisterHandlers register_handlers);
142 void WriteSummaryOffset(const SummaryOffset &offset);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700143
144 // Writes an MCAP record to the output file.
James Kuszmaulb3fba252022-04-06 15:13:31 -0700145 void WriteRecord(OpCode op, std::string_view record, std::ostream *ostream);
146 void WriteRecord(OpCode op, std::string_view record) {
147 WriteRecord(op, record, &output_);
148 }
149 // Adds an MCAP-spec string/byte-array/map/array of pairs/fixed-size integer
150 // to a buffer.
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700151 static void AppendString(FastStringBuilder *builder, std::string_view string);
James Kuszmaulb3fba252022-04-06 15:13:31 -0700152 static void AppendBytes(FastStringBuilder *builder, std::string_view bytes);
153 static void AppendChannelMap(FastStringBuilder *builder,
154 const std::map<uint16_t, uint64_t> &map);
155 static void AppendMessageIndices(
156 FastStringBuilder *builder,
157 const std::vector<std::pair<uint64_t, uint64_t>> &messages);
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700158 static void AppendInt16(FastStringBuilder *builder, uint16_t val);
159 static void AppendInt32(FastStringBuilder *builder, uint32_t val);
160 static void AppendInt64(FastStringBuilder *builder, uint64_t val);
161
James Kuszmaulb3fba252022-04-06 15:13:31 -0700162 aos::EventLoop *event_loop_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700163 std::ofstream output_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700164 const Serialization serialization_;
James Kuszmaul9f607c62022-10-27 17:01:55 -0700165 const CanonicalChannelNames canonical_channels_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700166 size_t total_message_bytes_ = 0;
167 std::map<const Channel *, size_t> total_channel_bytes_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700168 FastStringBuilder string_builder_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700169
170 // Earliest message observed in this logfile.
171 std::optional<aos::monotonic_clock::time_point> earliest_message_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700172 // Latest message observed in this logfile.
173 aos::monotonic_clock::time_point latest_message_ = aos::monotonic_clock::min_time;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700174 // Count of all messages on each channel, indexed by channel ID.
175 std::map<uint16_t, uint64_t> message_counts_;
James Kuszmaulc31d7362022-05-27 14:20:04 -0700176 std::map<uint16_t, std::unique_ptr<RawFetcher>> fetchers_;
James Kuszmaul36a25f42022-10-28 10:18:00 -0700177 // All currently-being-built chunks. Indexed by channel ID. This is used to
178 // segregate channels into separate chunks to support more efficient reading.
179 std::map<uint16_t, ChunkStatus> current_chunks_;
James Kuszmaulb3fba252022-04-06 15:13:31 -0700180 // ChunkIndex's for all fully written Chunks.
181 std::vector<ChunkIndex> chunk_indices_;
James Kuszmaule4aa01d2022-06-28 14:09:02 -0700182
183 // Metadata associated with the fake "configuration" channel that we create in
184 // order to ensure that foxglove extensions/users have access to the full
185 // configuration.
186 uint16_t configuration_id_ = 0;
187 FlatbufferDetachedBuffer<Channel> configuration_channel_;
188 FlatbufferDetachedBuffer<Configuration> configuration_;
James Kuszmaul4ed5fb12022-03-22 15:20:04 -0700189};
190} // namespace aos
191#endif // AOS_UTIL_MCAP_LOGGER_H_