-
Notifications
You must be signed in to change notification settings - Fork 106
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add mcap du
command
#1021
Merged
Merged
Add mcap du
command
#1021
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bf25d21
Add `mcap du` command
defunctzombie 15d848b
update
defunctzombie ee8bf94
Merge remote-tracking branch 'origin/main' into roman/add-du-command
defunctzombie 1e4d266
update
defunctzombie 3c1cc24
linter
defunctzombie af81a34
more lint
defunctzombie 30ac0e9
add long description
defunctzombie bac6c7e
lint
defunctzombie File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,301 @@ | ||
package cmd | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"errors" | ||
"fmt" | ||
"hash/crc32" | ||
"io" | ||
"os" | ||
"sort" | ||
|
||
"github.com/foxglove/mcap/go/cli/mcap/utils" | ||
"github.com/foxglove/mcap/go/mcap" | ||
"github.com/klauspost/compress/zstd" | ||
"github.com/pierrec/lz4/v4" | ||
"github.com/spf13/cobra" | ||
) | ||
|
||
type usage struct { | ||
reader io.ReadSeeker | ||
|
||
channels map[uint16]*mcap.Channel | ||
|
||
// total message size of all messages | ||
totalMessageSize uint64 | ||
|
||
// total message size by topic name | ||
topicMessageSize map[string]uint64 | ||
|
||
totalSize uint64 | ||
|
||
// record kind to size | ||
recordKindSize map[string]uint64 | ||
} | ||
|
||
func newUsage(reader io.ReadSeeker) *usage { | ||
return &usage{ | ||
reader: reader, | ||
channels: make(map[uint16]*mcap.Channel), | ||
topicMessageSize: make(map[string]uint64), | ||
recordKindSize: make(map[string]uint64), | ||
totalSize: 16, /* 8 bytes for leading magic and 8 bytes for trailing magic */ | ||
} | ||
} | ||
|
||
func (instance *usage) processChunk(chunk *mcap.Chunk) error { | ||
compressionFormat := mcap.CompressionFormat(chunk.Compression) | ||
var uncompressedBytes []byte | ||
|
||
switch compressionFormat { | ||
case mcap.CompressionNone: | ||
uncompressedBytes = chunk.Records | ||
case mcap.CompressionZSTD: | ||
compressedDataReader := bytes.NewReader(chunk.Records) | ||
chunkDataReader, err := zstd.NewReader(compressedDataReader) | ||
if err != nil { | ||
return fmt.Errorf("could not make zstd decoder: %w", err) | ||
} | ||
uncompressedBytes, err = io.ReadAll(chunkDataReader) | ||
if err != nil { | ||
return fmt.Errorf("could not decompress: %w", err) | ||
} | ||
case mcap.CompressionLZ4: | ||
var err error | ||
compressedDataReader := bytes.NewReader(chunk.Records) | ||
chunkDataReader := lz4.NewReader(compressedDataReader) | ||
uncompressedBytes, err = io.ReadAll(chunkDataReader) | ||
if err != nil { | ||
return fmt.Errorf("could not decompress: %w", err) | ||
} | ||
default: | ||
return fmt.Errorf("unsupported compression format: %s", chunk.Compression) | ||
} | ||
|
||
if uint64(len(uncompressedBytes)) != chunk.UncompressedSize { | ||
return fmt.Errorf("uncompressed chunk data size != Chunk.uncompressed_size") | ||
} | ||
|
||
if chunk.UncompressedCRC != 0 { | ||
crc := crc32.ChecksumIEEE(uncompressedBytes) | ||
if crc != chunk.UncompressedCRC { | ||
return fmt.Errorf("invalid CRC: %x != %x", crc, chunk.UncompressedCRC) | ||
} | ||
} | ||
|
||
uncompressedBytesReader := bytes.NewReader(uncompressedBytes) | ||
|
||
lexer, err := mcap.NewLexer(uncompressedBytesReader, &mcap.LexerOptions{ | ||
SkipMagic: true, | ||
ValidateChunkCRCs: true, | ||
EmitChunks: true, | ||
}) | ||
if err != nil { | ||
return fmt.Errorf("failed to make lexer for chunk bytes: %w", err) | ||
} | ||
defer lexer.Close() | ||
|
||
msg := make([]byte, 1024) | ||
for { | ||
tokenType, data, err := lexer.Next(msg) | ||
if err != nil { | ||
if errors.Is(err, io.EOF) { | ||
break | ||
} | ||
return fmt.Errorf("failed to read next token: %w", err) | ||
} | ||
if len(data) > len(msg) { | ||
msg = data | ||
} | ||
|
||
switch tokenType { | ||
case mcap.TokenChannel: | ||
channel, err := mcap.ParseChannel(data) | ||
if err != nil { | ||
return fmt.Errorf("Error parsing Channel: %w", err) | ||
} | ||
|
||
instance.channels[channel.ID] = channel | ||
case mcap.TokenMessage: | ||
message, err := mcap.ParseMessage(data) | ||
if err != nil { | ||
return fmt.Errorf("Error parsing Message: %w", err) | ||
} | ||
|
||
channel := instance.channels[message.ChannelID] | ||
if channel == nil { | ||
return fmt.Errorf("got a Message record for unknown channel: %d", message.ChannelID) | ||
} | ||
|
||
messageSize := uint64(len(message.Data)) | ||
|
||
instance.totalMessageSize += messageSize | ||
instance.topicMessageSize[channel.Topic] += messageSize | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (instance *usage) RunDu() error { | ||
lexer, err := mcap.NewLexer(instance.reader, &mcap.LexerOptions{ | ||
SkipMagic: false, | ||
ValidateChunkCRCs: true, | ||
EmitChunks: true, | ||
}) | ||
if err != nil { | ||
return err | ||
} | ||
defer lexer.Close() | ||
|
||
msg := make([]byte, 1024) | ||
for { | ||
tokenType, data, err := lexer.Next(msg) | ||
if err != nil { | ||
if errors.Is(err, io.EOF) { | ||
break | ||
} | ||
|
||
return fmt.Errorf("failed to read next token: %w", err) | ||
} | ||
if len(data) > len(msg) { | ||
msg = data | ||
} | ||
|
||
instance.totalSize += uint64(len(data)) | ||
instance.recordKindSize[tokenType.String()] += uint64(len(data)) | ||
|
||
switch tokenType { | ||
case mcap.TokenChannel: | ||
channel, err := mcap.ParseChannel(data) | ||
if err != nil { | ||
return fmt.Errorf("error parsing Channel: %w", err) | ||
} | ||
|
||
instance.channels[channel.ID] = channel | ||
case mcap.TokenMessage: | ||
message, err := mcap.ParseMessage(data) | ||
if err != nil { | ||
return fmt.Errorf("error parsing Message: %w", err) | ||
} | ||
channel := instance.channels[message.ChannelID] | ||
if channel == nil { | ||
return fmt.Errorf("got a Message record for unknown channel: %d", message.ChannelID) | ||
} | ||
|
||
messageSize := uint64(len(message.Data)) | ||
|
||
instance.totalMessageSize += messageSize | ||
instance.topicMessageSize[channel.Topic] += messageSize | ||
case mcap.TokenChunk: | ||
chunk, err := mcap.ParseChunk(data) | ||
if err != nil { | ||
return fmt.Errorf("error parsing Message: %w", err) | ||
} | ||
err = instance.processChunk(chunk) | ||
if err != nil { | ||
return err | ||
} | ||
} | ||
} | ||
|
||
fmt.Println("Top level record stats:") | ||
fmt.Println() | ||
|
||
{ | ||
rows := [][]string{} | ||
rows = append(rows, []string{ | ||
"record", | ||
"sum bytes", | ||
"% of total file bytes", | ||
}, []string{ | ||
"------", | ||
"---------", | ||
"---------------------", | ||
}) | ||
|
||
for recordKind, size := range instance.recordKindSize { | ||
row := []string{ | ||
recordKind, fmt.Sprintf("%d", size), | ||
fmt.Sprintf("%f", float32(size)/float32(instance.totalSize)*100.0), | ||
} | ||
|
||
rows = append(rows, row) | ||
} | ||
|
||
utils.FormatTable(os.Stdout, rows) | ||
} | ||
|
||
fmt.Println() | ||
fmt.Println("Message size stats:") | ||
fmt.Println() | ||
|
||
{ | ||
rows := [][]string{} | ||
rows = append(rows, []string{ | ||
"topic", | ||
"sum bytes (uncompressed)", | ||
"% of total message bytes (uncompressed)", | ||
}, []string{ | ||
"-----", | ||
"------------------------", | ||
"---------------------------------------", | ||
}) | ||
|
||
type topicInfo struct { | ||
name string | ||
size uint64 | ||
} | ||
topicInfos := make([]topicInfo, 0, len(instance.topicMessageSize)) | ||
for topic, size := range instance.topicMessageSize { | ||
topicInfos = append(topicInfos, topicInfo{topic, size}) | ||
} | ||
|
||
// Sort for largest topics first | ||
sort.Slice(topicInfos, func(i, j int) bool { | ||
return topicInfos[i].size > topicInfos[j].size | ||
}) | ||
|
||
for _, info := range topicInfos { | ||
row := []string{ | ||
info.name, | ||
humanBytes(info.size), | ||
fmt.Sprintf("%f", float32(info.size)/float32(instance.totalMessageSize)*100.0), | ||
} | ||
|
||
rows = append(rows, row) | ||
} | ||
|
||
utils.FormatTable(os.Stdout, rows) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
var duCmd = &cobra.Command{ | ||
Use: "du <file>", | ||
Short: "Report space usage within an MCAP file", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please also add a |
||
Long: `This command reports space usage within an mcap file. Space usage for messages is | ||
calculated using the uncompressed size. | ||
|
||
Note: This command will scan and uncompress the entire file.`, | ||
Run: func(_ *cobra.Command, args []string) { | ||
ctx := context.Background() | ||
if len(args) != 1 { | ||
die("Unexpected number of args") | ||
} | ||
filename := args[0] | ||
err := utils.WithReader(ctx, filename, func(_ bool, rs io.ReadSeeker) error { | ||
usage := newUsage(rs) | ||
return usage.RunDu() | ||
}) | ||
if err != nil { | ||
die("Failed to read file %s: %v", filename, err) | ||
} | ||
}, | ||
} | ||
|
||
func init() { | ||
rootCmd.AddCommand(duCmd) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
totally pedantic, but if we're going to come up with totalSize by summing up all the bytes that come out of the lexer, we'll need to add 8 bytes each for the header and trailer magic.