-
Notifications
You must be signed in to change notification settings - Fork 77
/
mcap_amendment.go
452 lines (415 loc) · 14 KB
/
mcap_amendment.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package utils
import (
"bytes"
"encoding/binary"
"fmt"
"hash/crc32"
"io"
"github.com/foxglove/mcap/go/mcap"
)
const (
SizeRecordLength = 8
SizeOpcode = 1
SizeDataEnd = 4
SizeFooter = 8 + 8 + 4
SizeMagic = 8
)
// AmendMCAP adds attachment and metadata records to the end of the
// data section of an existing MCAP, in place. It then writes a new summary
// section consisting of the existing summary section, plus new attachment and
// metadata index records as applicable, with all offsets and CRCs updated to
// account for the new data.
func AmendMCAP(
wsc io.ReadWriteSeeker,
attachments []*mcap.Attachment,
metadata []*mcap.Metadata,
) error {
lexer, err := mcap.NewLexer(wsc, &mcap.LexerOptions{
SkipMagic: true,
})
if err != nil {
return fmt.Errorf("failed to build lexer: %w", err)
}
defer lexer.Close()
oldFooter, err := readFooter(wsc)
if err != nil {
return fmt.Errorf("failed to read footer: %w", err)
}
oldSummaryStart := oldFooter.SummaryStart
// seek to the opcode of the data end record
oldDataEndOffset := int64(oldSummaryStart - SizeDataEnd - SizeRecordLength - SizeOpcode)
oldDataEnd, err := readDataEnd(wsc, oldDataEndOffset)
if err != nil {
return fmt.Errorf("failed to read data end: %w", err)
}
// Now we are at the old summary start. Parse from here to EOF into a
// summarySection structure.
summary, err := readSummarySection(wsc)
if err != nil {
return fmt.Errorf("failed to read summary section: %w", err)
}
// Seek to the location of the old data end record. We will write the new data section records starting here.
_, err = wsc.Seek(oldDataEndOffset, io.SeekStart)
if err != nil {
return fmt.Errorf("failed to seek to data end: %w", err)
}
extraDataLength, attachmentIndexes, metadataIndexes, err := extendDataSection(
wsc,
oldDataEndOffset,
oldDataEnd.DataSectionCRC,
attachments,
metadata,
)
if err != nil {
return fmt.Errorf("failed to build extra data: %w", err)
}
// the new summary offset is the old data end offset plus the length just written.
newSummaryOffset := oldDataEndOffset + extraDataLength
// Update summary with the new attachment and metadata indexes.
for _, attachmentIndex := range attachmentIndexes {
summary.AttachmentIndexes = append(summary.AttachmentIndexes, attachmentIndex)
summary.Statistics.AttachmentCount++
}
for _, metadataIndex := range metadataIndexes {
summary.MetadataIndexes = append(summary.MetadataIndexes, metadataIndex)
summary.Statistics.MetadataCount++
}
// Write summary out into a well-formed summary section, with all offsets and CRCs updated.
err = writeSummaryBytes(wsc, summary, newSummaryOffset)
if err != nil {
return fmt.Errorf("failed to build new summary section: %w", err)
}
return nil
}
// summarySection is a structure that contains all the records in the summary
// section of an MCAP.
type summarySection struct {
Channels []*mcap.Channel
Schemas []*mcap.Schema
AttachmentIndexes []*mcap.AttachmentIndex
MetadataIndexes []*mcap.MetadataIndex
ChunkIndexes []*mcap.ChunkIndex
SummaryOffsets []*mcap.SummaryOffset
Statistics *mcap.Statistics
Footer *mcap.Footer
}
// readSummarySection reads MCAP data into a summary section structure. The
// reader should be positioned at the start of the summary section, and must be
// positioned at the start of a record.
func readSummarySection(r io.Reader) (*summarySection, error) {
lexer, err := mcap.NewLexer(r, &mcap.LexerOptions{
SkipMagic: true,
})
if err != nil {
return nil, fmt.Errorf("failed to construct summary section lexer: %w", err)
}
result := summarySection{}
for {
tokenType, token, err := lexer.Next(nil)
if err != nil {
return nil, fmt.Errorf("failed to pull next record: %w", err)
}
switch tokenType {
case mcap.TokenChannel:
record, err := mcap.ParseChannel(token)
if err != nil {
return nil, fmt.Errorf("failed to parse channel: %w", err)
}
result.Channels = append(result.Channels, record)
case mcap.TokenSchema:
record, err := mcap.ParseSchema(token)
if err != nil {
return nil, fmt.Errorf("failed to parse schema: %w", err)
}
result.Schemas = append(result.Schemas, record)
case mcap.TokenChunkIndex:
record, err := mcap.ParseChunkIndex(token)
if err != nil {
return nil, fmt.Errorf("failed to parse chunk index: %w", err)
}
result.ChunkIndexes = append(result.ChunkIndexes, record)
case mcap.TokenAttachmentIndex:
record, err := mcap.ParseAttachmentIndex(token)
if err != nil {
return nil, fmt.Errorf("failed to parse attachment index: %w", err)
}
result.AttachmentIndexes = append(result.AttachmentIndexes, record)
case mcap.TokenMetadataIndex:
record, err := mcap.ParseMetadataIndex(token)
if err != nil {
return nil, fmt.Errorf("failed to parse metadata index: %w", err)
}
result.MetadataIndexes = append(result.MetadataIndexes, record)
case mcap.TokenSummaryOffset:
record, err := mcap.ParseSummaryOffset(token)
if err != nil {
return nil, fmt.Errorf("failed to parse summary offset: %w", err)
}
result.SummaryOffsets = append(result.SummaryOffsets, record)
case mcap.TokenStatistics:
record, err := mcap.ParseStatistics(token)
if err != nil {
return nil, fmt.Errorf("failed to parse statistics: %w", err)
}
result.Statistics = record
case mcap.TokenFooter:
record, err := mcap.ParseFooter(token)
if err != nil {
return nil, fmt.Errorf("failed to parse footer: %w", err)
}
result.Footer = record
return &result, nil
}
}
}
// buildSummaryBytes constructs a summary byte section from a summarySection
// structure, including the footer and closing magic, given a start offset. The
// sections/offset groups may be rewritten in a different order than the in the
// data the summarySection was originally parsed from. All offsets and CRCs are
// updated to account.
func writeSummaryBytes(w io.Writer, section *summarySection, summaryStart int64) error {
wc := newChecksummingWriteCounter(w, 0)
writer, err := mcap.NewWriter(wc, &mcap.WriterOptions{
SkipMagic: true,
})
if err != nil {
return fmt.Errorf("failed to construct summary section writer: %w", err)
}
fileOffset := summaryStart
summaryInset := int64(0)
summaryOffsets := []*mcap.SummaryOffset{}
for _, schema := range section.Schemas {
err := writer.WriteSchema(schema)
if err != nil {
return fmt.Errorf("failed to write schema: %w", err)
}
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpSchema,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryInset = wc.Count()
for _, channel := range section.Channels {
err := writer.WriteChannel(channel)
if err != nil {
return fmt.Errorf("failed to write channel: %w", err)
}
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpChannel,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryInset = wc.Count()
for _, attachmentIndex := range section.AttachmentIndexes {
err := writer.WriteAttachmentIndex(attachmentIndex)
if err != nil {
return fmt.Errorf("failed to write attachment index: %w", err)
}
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpAttachmentIndex,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryInset = wc.Count()
for _, metadataIndex := range section.MetadataIndexes {
err := writer.WriteMetadataIndex(metadataIndex)
if err != nil {
return fmt.Errorf("failed to write metadata index: %w", err)
}
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpMetadataIndex,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryInset = wc.Count()
for _, chunkIndex := range section.ChunkIndexes {
err := writer.WriteChunkIndex(chunkIndex)
if err != nil {
return fmt.Errorf("failed to write chunk index: %w", err)
}
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpChunkIndex,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryInset = wc.Count()
err = writer.WriteStatistics(section.Statistics)
if err != nil {
return fmt.Errorf("failed to write statistics: %w", err)
}
summaryOffsets = append(summaryOffsets, &mcap.SummaryOffset{
GroupOpcode: mcap.OpStatistics,
GroupStart: uint64(fileOffset),
GroupLength: uint64(wc.Count()) - uint64(summaryInset),
})
fileOffset += wc.Count() - summaryInset
summaryOffsetStart := fileOffset
for _, summaryOffset := range summaryOffsets {
err := writer.WriteSummaryOffset(summaryOffset)
if err != nil {
return fmt.Errorf("failed to write summary offset: %w", err)
}
}
// Only compute a CRC if the existing CRC is nonzero. Interpret zero to mean
// CRCs disabled.
var summaryCRC uint32
if section.Footer.SummaryCRC != 0 {
summaryCRC = wc.CRC()
}
footer := &mcap.Footer{
SummaryStart: uint64(summaryStart),
SummaryOffsetStart: uint64(summaryOffsetStart),
SummaryCRC: summaryCRC,
}
err = writeFooter(wc, footer)
if err != nil {
return fmt.Errorf("failed to write footer: %w", err)
}
_, err = wc.Write(mcap.Magic)
if err != nil {
return fmt.Errorf("failed to write closing magic: %w", err)
}
return nil
}
// writeFooter writes a footer record onto a writer, updating the attached CRC
// to include the initial bytes.
func writeFooter(w io.Writer, footer *mcap.Footer) error {
buf := make([]byte, 29)
buf[0] = byte(mcap.OpFooter)
inset := 1
binary.LittleEndian.PutUint64(buf[inset:], 20)
inset += 8
binary.LittleEndian.PutUint64(buf[inset:], footer.SummaryStart)
inset += 8
binary.LittleEndian.PutUint64(buf[inset:], footer.SummaryOffsetStart)
inset += 8
var crc uint32
if footer.SummaryCRC > 0 {
crc = crc32.Update(footer.SummaryCRC, crc32.IEEETable, buf[:inset])
}
binary.LittleEndian.PutUint32(buf[inset:], crc)
inset += 4
if _, err := w.Write(buf[:inset]); err != nil {
return err
}
return nil
}
// readFooter reads the footer record from the end of an MCAP.
func readFooter(rs io.ReadSeeker) (*mcap.Footer, error) {
_, err := rs.Seek(-SizeMagic-SizeFooter, io.SeekEnd)
if err != nil {
return nil, fmt.Errorf("failed to seek to footer: %w", err)
}
if err != nil {
return nil, fmt.Errorf("failed to construct lexer: %w", err)
}
buf := make([]byte, 28)
_, err = io.ReadFull(rs, buf)
if err != nil {
return nil, fmt.Errorf("failed to read footer: %w", err)
}
if !bytes.Equal(buf[20:], mcap.Magic) {
return nil, fmt.Errorf("invalid magic")
}
footer, err := mcap.ParseFooter(buf[:20])
if err != nil {
return nil, fmt.Errorf("failed to parse footer: %w", err)
}
return footer, nil
}
// readDataEnd reads a data end record at the supplied offset.
func readDataEnd(rs io.ReadSeeker, offset int64) (*mcap.DataEnd, error) {
_, err := rs.Seek(offset, io.SeekStart)
if err != nil {
return nil, fmt.Errorf("failed to seek to data end: %w", err)
}
buf := make([]byte, SizeOpcode+SizeRecordLength+SizeDataEnd)
_, err = io.ReadFull(rs, buf)
if err != nil {
return nil, fmt.Errorf("failed to read data end: %w", err)
}
if buf[0] != byte(mcap.OpDataEnd) {
return nil, fmt.Errorf("expected data end opcode but got %d", mcap.OpCode(buf[0]))
}
dataEnd, err := mcap.ParseDataEnd(buf[SizeOpcode+SizeRecordLength:])
if err != nil {
return nil, fmt.Errorf("failed to parse data end: %w", err)
}
return dataEnd, nil
}
// extendDataSection writes attachments and metadata records over an existing
// DataEnd record, and then writes its own DataEnd at the end. It returns slices
// of attachment and metadata indexes. The startOffset supplied is used to
// compute offsets in these indexes, and startCRC - expected to be the CRC of
// the existing data section - is updated with new writes and added to the new
// data section.
func extendDataSection(
w io.Writer,
startOffset int64,
startCRC uint32,
attachments []*mcap.Attachment,
metadata []*mcap.Metadata,
) (int64, []*mcap.AttachmentIndex, []*mcap.MetadataIndex, error) {
cw := newChecksummingWriteCounter(w, startCRC)
writer, err := mcap.NewWriter(cw, &mcap.WriterOptions{
SkipMagic: true,
})
if err != nil {
return cw.Count(), nil, nil, fmt.Errorf("failed to construct writer: %w", err)
}
attachmentIndexes := make([]*mcap.AttachmentIndex, 0, len(attachments))
for _, attachment := range attachments {
offset := cw.Count()
attachmentIndex := &mcap.AttachmentIndex{
Offset: uint64(offset) + uint64(startOffset),
LogTime: attachment.LogTime,
CreateTime: attachment.CreateTime,
DataSize: attachment.DataSize,
Name: attachment.Name,
MediaType: attachment.MediaType,
}
err := writer.WriteAttachment(attachment)
if err != nil {
return cw.Count(), nil, nil, fmt.Errorf("failed to write attachment: %w", err)
}
attachmentIndex.Length = uint64(cw.Count() - offset)
attachmentIndexes = append(attachmentIndexes, attachmentIndex)
}
metadataIndexes := make([]*mcap.MetadataIndex, 0, len(metadata))
for _, metadata := range metadata {
offset := cw.Count()
metadataIndex := &mcap.MetadataIndex{
Offset: uint64(offset) + uint64(startOffset),
Name: metadata.Name,
}
err := writer.WriteMetadata(metadata)
if err != nil {
return cw.Count(), nil, nil, fmt.Errorf("failed to write metadata: %w", err)
}
metadataIndex.Length = uint64(cw.Count() - offset)
metadataIndexes = append(metadataIndexes, metadataIndex)
}
// Only compute a CRC if the initial CRC is nonzero, otherwise leave it as zero.
var dataSectionCRC uint32
if startCRC != 0 {
dataSectionCRC = cw.CRC()
}
newDataEnd := &mcap.DataEnd{
DataSectionCRC: dataSectionCRC,
}
err = writer.WriteDataEnd(newDataEnd)
if err != nil {
return cw.Count(), nil, nil, fmt.Errorf("failed to write data end: %w", err)
}
return cw.Count(), attachmentIndexes, metadataIndexes, nil
}