-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
667 lines (623 loc) · 16.6 KB
/
Copy pathparser.go
File metadata and controls
667 lines (623 loc) · 16.6 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
package ulogo
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
// Option changes ULog parsing behavior.
type Option func(*loadOptions)
type loadOptions struct {
messageFilter map[string]struct{}
headerOnly bool
}
// WithMessageFilter loads data streams only for the given topic names.
// A nil filter loads every stream. An empty filter loads definitions only.
func WithMessageFilter(names []string) Option {
return func(opts *loadOptions) {
if names == nil {
opts.messageFilter = nil
return
}
opts.messageFilter = make(map[string]struct{}, len(names))
for _, name := range names {
opts.messageFilter[name] = struct{}{}
}
}
}
// HeaderOnly stops after the definition section.
func HeaderOnly() Option {
return func(opts *loadOptions) {
opts.headerOnly = true
}
}
// Load opens and parses a ULog file.
func Load(filename string, options ...Option) (*ULog, error) {
return ReadFile(filename, options...)
}
// ReadFile opens and parses a ULog file.
func ReadFile(filename string, options ...Option) (*ULog, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return Read(file, options...)
}
// Read parses ULog data from reader.
//
// If reader implements io.ReadSeeker, Read parses directly from it. Otherwise
// Read buffers the input in memory and parses from that buffer, which keeps the
// API usable for network, archive, and in-memory inputs without writing a
// temporary file. ULog appended data requires seeking, so truly streaming
// parsing is exposed separately from the full in-memory ULog parser.
func Read(reader io.Reader, options ...Option) (*ULog, error) {
if reader == nil {
return nil, fmt.Errorf("nil reader")
}
if seeker, ok := reader.(io.ReadSeeker); ok {
return readSeek(seeker, options...)
}
raw, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
return readSeek(bytes.NewReader(raw), options...)
}
func readSeek(reader io.ReadSeeker, options ...Option) (*ULog, error) {
opts := loadOptions{}
for _, option := range options {
option(&opts)
}
log := newULog()
p := parser{
reader: reader,
log: log,
opts: opts,
subscriptions: map[uint16]*subscription{},
filteredIDs: map[uint16]struct{}{},
missingIDs: map[uint16]struct{}{},
}
if err := p.readHeader(); err != nil {
return nil, err
}
log.LastTimestamp = log.StartTimestamp
if err := p.readDefinitions(); err != nil {
return nil, err
}
if opts.headerOnly {
return log, nil
}
if log.HasDataAppended() && len(log.AppendedOffsets) > 0 {
for _, offset := range log.AppendedOffsets {
if err := p.readData(int64(offset)); err != nil {
return nil, err
}
if _, err := p.reader.Seek(int64(offset), io.SeekStart); err != nil {
return nil, err
}
}
}
if err := p.readData(1 << 62); err != nil {
return nil, err
}
p.flushDatasets()
sort.Slice(log.Data, func(i, j int) bool {
if log.Data[i].Name == log.Data[j].Name {
return log.Data[i].MultiID < log.Data[j].MultiID
}
return log.Data[i].Name < log.Data[j].Name
})
return log, nil
}
type parser struct {
reader io.ReadSeeker
log *ULog
opts loadOptions
subscriptions map[uint16]*subscription
filteredIDs map[uint16]struct{}
missingIDs map[uint16]struct{}
}
type messageHeader struct {
size uint16
typ byte
}
type subscription struct {
multiID byte
msgID uint16
messageName string
fields []FlatField
timestampIndex int
timestampOffset int
minDataSize int
rows []Row
}
func (p *parser) readHeader() error {
header := make([]byte, 16)
if _, err := io.ReadFull(p.reader, header); err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, io.EOF) {
return fmt.Errorf("invalid ULog file: header too short")
}
return err
}
if !bytes.Equal(header[:7], HeaderBytes) {
return fmt.Errorf("invalid ULog file: bad header magic")
}
p.log.Version = header[7]
p.log.StartTimestamp = binary.LittleEndian.Uint64(header[8:16])
return nil
}
func (p *parser) readDefinitions() error {
for {
header, err := p.readMessageHeader()
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
data, err := p.readMessageData(header)
if err != nil {
return err
}
switch header.typ {
case msgTypeInfo:
info, err := parseInfo(data, false)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.Info[info.key] = info.value
p.log.InfoTypes[info.key] = info.value.Type
case msgTypeInfoMultiple:
info, err := parseInfo(data, true)
if err != nil {
p.log.FileCorruption = true
continue
}
p.addInfoMultiple(info)
case msgTypeFormat:
format, err := parseFormat(data)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.MessageFormats[format.Name] = format
case msgTypeParameter:
param, err := parseInfo(data, false)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.InitialParameters[param.key] = param.value
case msgTypeParameterDefault:
if err := p.addDefaultParameter(data); err != nil {
p.log.FileCorruption = true
}
case msgTypeFlagBits:
p.parseFlags(data)
case msgTypeAddLogged, msgTypeLogging, msgTypeLoggingTagged:
_, _ = p.reader.Seek(-int64(3+header.size), io.SeekCurrent)
return nil
default:
if packetLooksCorrupt(header) {
p.log.FileCorruption = true
_, _ = p.reader.Seek(-int64(2+header.size), io.SeekCurrent)
}
}
}
}
func (p *parser) readData(readUntil int64) error {
for {
start, _ := p.reader.Seek(0, io.SeekCurrent)
header, err := p.readMessageHeader()
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
data, err := p.readMessageData(header)
if err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil
}
return err
}
end, _ := p.reader.Seek(0, io.SeekCurrent)
if end > readUntil {
_, _ = p.reader.Seek(start, io.SeekStart)
return nil
}
switch header.typ {
case msgTypeInfo:
info, err := parseInfo(data, false)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.Info[info.key] = info.value
p.log.InfoTypes[info.key] = info.value.Type
case msgTypeInfoMultiple:
info, err := parseInfo(data, true)
if err != nil {
p.log.FileCorruption = true
continue
}
p.addInfoMultiple(info)
case msgTypeParameter:
param, err := parseInfo(data, false)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.ChangedParameters = append(p.log.ChangedParameters, ChangedParameter{
Timestamp: p.log.LastTimestamp,
Name: param.key,
Value: param.value,
})
case msgTypeParameterDefault:
if err := p.addDefaultParameter(data); err != nil {
p.log.FileCorruption = true
}
case msgTypeAddLogged:
sub, err := p.parseAddLogged(data)
if err != nil {
p.log.FileCorruption = true
continue
}
if p.acceptsMessage(sub.messageName) {
p.subscriptions[sub.msgID] = sub
} else {
p.filteredIDs[sub.msgID] = struct{}{}
}
case msgTypeLogging:
msg, err := parseLogging(data)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.LoggedMessages = append(p.log.LoggedMessages, msg)
case msgTypeLoggingTagged:
msg, err := parseTaggedLogging(data)
if err != nil {
p.log.FileCorruption = true
continue
}
p.log.LoggedMessagesTagged[msg.Tag] = append(p.log.LoggedMessagesTagged[msg.Tag], msg)
case msgTypeData:
timestamp, err := p.parseData(data)
if err != nil {
p.log.FileCorruption = true
continue
}
if timestamp > p.log.LastTimestamp {
p.log.LastTimestamp = timestamp
}
case msgTypeDropout:
if len(data) >= 2 {
p.log.Dropouts = append(p.log.Dropouts, Dropout{
Timestamp: p.log.LastTimestamp,
Duration: binary.LittleEndian.Uint16(data[:2]),
})
}
case msgTypeSync:
p.log.SyncCount++
case msgTypeRemoveLogged:
// pyulog currently keeps already decoded data and ignores remove messages.
default:
if packetLooksCorrupt(header) {
p.log.FileCorruption = true
}
}
}
}
func (p *parser) readMessageHeader() (messageHeader, error) {
var buf [3]byte
n, err := io.ReadFull(p.reader, buf[:])
if err != nil {
if errors.Is(err, io.EOF) || (errors.Is(err, io.ErrUnexpectedEOF) && n == 0) {
return messageHeader{}, io.EOF
}
return messageHeader{}, err
}
return messageHeader{size: binary.LittleEndian.Uint16(buf[:2]), typ: buf[2]}, nil
}
func (p *parser) readMessageData(header messageHeader) ([]byte, error) {
data := make([]byte, int(header.size))
_, err := io.ReadFull(p.reader, data)
return data, err
}
func (p *parser) parseFlags(data []byte) {
if len(data) < 40 {
p.log.FileCorruption = true
return
}
copy(p.log.CompatFlags[:], data[:8])
copy(p.log.IncompatFlags[:], data[8:16])
p.log.AppendedOffsets = p.log.AppendedOffsets[:0]
for i := 0; i < 3; i++ {
offset := binary.LittleEndian.Uint64(data[16+i*8 : 24+i*8])
if offset != 0 {
p.log.AppendedOffsets = append(p.log.AppendedOffsets, offset)
}
}
}
func (p *parser) addInfoMultiple(info parsedInfo) {
if _, ok := p.log.InfoMultiple[info.key]; !ok {
p.log.InfoMultiple[info.key] = [][]Value{{info.value}}
p.log.InfoMultipleTypes[info.key] = info.value.Type
return
}
if info.continued && len(p.log.InfoMultiple[info.key]) > 0 {
last := len(p.log.InfoMultiple[info.key]) - 1
p.log.InfoMultiple[info.key][last] = append(p.log.InfoMultiple[info.key][last], info.value)
return
}
p.log.InfoMultiple[info.key] = append(p.log.InfoMultiple[info.key], []Value{info.value})
}
func (p *parser) addDefaultParameter(data []byte) error {
if len(data) < 2 {
return fmt.Errorf("parameter default too short")
}
defaultTypes := data[0]
info, err := parseInfo(data[1:], false)
if err != nil {
return err
}
for defaultTypes != 0 {
bit := defaultTypes & -defaultTypes
defaultTypes ^= bit
defaultType := int(bit - 1)
if p.log.DefaultParameters[defaultType] == nil {
p.log.DefaultParameters[defaultType] = map[string]Value{}
}
p.log.DefaultParameters[defaultType][info.key] = info.value
}
return nil
}
func (p *parser) parseAddLogged(data []byte) (*subscription, error) {
if len(data) < 3 {
return nil, fmt.Errorf("add logged message too short")
}
sub := &subscription{
multiID: data[0],
msgID: binary.LittleEndian.Uint16(data[1:3]),
messageName: string(data[3:]),
timestampIndex: -1,
}
if err := p.flattenFields("", sub.messageName, &sub.fields); err != nil {
return nil, err
}
for len(sub.fields) > 0 && strings.HasPrefix(sub.fields[len(sub.fields)-1].Name, "_padding") {
sub.fields = sub.fields[:len(sub.fields)-1]
}
offset := 0
for i := range sub.fields {
sub.fields[i].Offset = offset
if sub.fields[i].Name == "timestamp" {
sub.timestampIndex = i
sub.timestampOffset = offset
}
offset += sub.fields[i].Size
}
sub.minDataSize = offset
return sub, nil
}
func (p *parser) flattenFields(prefix, typeName string, out *[]FlatField) error {
format, ok := p.log.MessageFormats[typeName]
if !ok {
return fmt.Errorf("missing message format for %q", typeName)
}
for _, field := range format.Fields {
if isPrimitive(field.Type) {
size, _ := FieldSize(field.Type)
if field.ArraySize > 0 {
for i := 0; i < field.ArraySize; i++ {
*out = append(*out, FlatField{
Name: prefix + field.Name + "[" + strconv.Itoa(i) + "]",
Type: field.Type,
Size: size,
})
}
continue
}
*out = append(*out, FlatField{
Name: prefix + field.Name,
Type: field.Type,
Size: size,
})
continue
}
if field.ArraySize > 0 {
for i := 0; i < field.ArraySize; i++ {
if err := p.flattenFields(prefix+field.Name+"["+strconv.Itoa(i)+"].", field.Type, out); err != nil {
return err
}
}
continue
}
if err := p.flattenFields(prefix+field.Name+".", field.Type, out); err != nil {
return err
}
}
return nil
}
func (p *parser) parseData(data []byte) (uint64, error) {
if len(data) < 2 {
return 0, fmt.Errorf("data message too short")
}
msgID := binary.LittleEndian.Uint16(data[:2])
sub, ok := p.subscriptions[msgID]
if !ok {
if _, filtered := p.filteredIDs[msgID]; !filtered {
p.missingIDs[msgID] = struct{}{}
return 0, fmt.Errorf("no subscription for message id %d", msgID)
}
return 0, nil
}
payload := data[2:]
if len(payload) < sub.minDataSize {
return 0, fmt.Errorf("data message for %s too short: have %d need %d", sub.messageName, len(payload), sub.minDataSize)
}
if len(payload) > sub.minDataSize {
payload = payload[:sub.minDataSize]
}
row := Row{Values: make([]Value, len(sub.fields))}
for i, field := range sub.fields {
value, err := decodePrimitive(field.Type, payload[field.Offset:field.Offset+field.Size])
if err != nil {
return 0, err
}
row.Values[i] = value
if i == sub.timestampIndex {
switch ts := value.Any.(type) {
case uint64:
row.Timestamp = ts
case uint32:
row.Timestamp = uint64(ts)
case int64:
row.Timestamp = uint64(ts)
case int32:
row.Timestamp = uint64(ts)
}
}
}
sub.rows = append(sub.rows, row)
return row.Timestamp, nil
}
func (p *parser) flushDatasets() {
for _, sub := range p.subscriptions {
if len(sub.rows) == 0 {
continue
}
p.log.Data = append(p.log.Data, Dataset{
Name: sub.messageName,
MultiID: sub.multiID,
MsgID: sub.msgID,
Fields: append([]FlatField(nil), sub.fields...),
TimestampIndex: sub.timestampIndex,
Rows: append([]Row(nil), sub.rows...),
})
}
}
func (p *parser) acceptsMessage(name string) bool {
if p.opts.messageFilter == nil {
return true
}
_, ok := p.opts.messageFilter[name]
return ok
}
func packetLooksCorrupt(header messageHeader) bool {
return header.typ == 0 || header.size == 0 || header.size > 10000
}
type parsedInfo struct {
key string
value Value
continued bool
}
func parseInfo(data []byte, multiple bool) (parsedInfo, error) {
info := parsedInfo{}
if multiple {
if len(data) < 2 {
return info, fmt.Errorf("info multiple too short")
}
info.continued = data[0] != 0
data = data[1:]
}
if len(data) < 1 {
return info, fmt.Errorf("info too short")
}
keyLen := int(data[0])
if len(data) < 1+keyLen {
return info, fmt.Errorf("info key too short")
}
typeKey := string(data[1 : 1+keyLen])
parts := strings.SplitN(typeKey, " ", 2)
if len(parts) != 2 {
return info, fmt.Errorf("invalid info key %q", typeKey)
}
value, err := decodeInfoValue(parts[0], data[1+keyLen:])
if err != nil {
return info, err
}
info.key = parts[1]
info.value = value
return info, nil
}
func decodeInfoValue(typeName string, data []byte) (Value, error) {
if strings.HasPrefix(typeName, "char[") {
return Value{Type: typeName, Any: trimCString(string(data))}, nil
}
if strings.Contains(typeName, "[") {
raw := append([]byte(nil), data...)
return Value{Type: typeName, Raw: raw}, nil
}
return decodePrimitive(typeName, data)
}
func parseFormat(data []byte) (MessageFormat, error) {
text := string(data)
name, rest, ok := strings.Cut(text, ":")
if !ok || name == "" {
return MessageFormat{}, fmt.Errorf("invalid format message %q", text)
}
format := MessageFormat{Name: name}
for _, raw := range strings.Split(rest, ";") {
raw = strings.TrimSpace(raw)
if raw == "" {
continue
}
field, err := parseField(raw)
if err != nil {
return MessageFormat{}, err
}
format.Fields = append(format.Fields, field)
}
return format, nil
}
func parseField(raw string) (Field, error) {
parts := strings.Fields(raw)
if len(parts) != 2 {
return Field{}, fmt.Errorf("invalid field %q", raw)
}
field := Field{Name: parts[1], Type: parts[0]}
if idx := strings.IndexByte(field.Type, '['); idx >= 0 {
end := strings.IndexByte(field.Type[idx:], ']')
if end < 0 {
return Field{}, fmt.Errorf("invalid array field %q", raw)
}
size, err := strconv.Atoi(field.Type[idx+1 : idx+end])
if err != nil {
return Field{}, fmt.Errorf("invalid array size in %q: %w", raw, err)
}
field.ArraySize = size
field.Type = field.Type[:idx]
}
return field, nil
}
func parseLogging(data []byte) (LoggingMessage, error) {
if len(data) < 9 {
return LoggingMessage{}, fmt.Errorf("logging message too short")
}
return LoggingMessage{
LogLevel: data[0],
Timestamp: binary.LittleEndian.Uint64(data[1:9]),
Message: string(data[9:]),
}, nil
}
func parseTaggedLogging(data []byte) (TaggedLoggingMessage, error) {
if len(data) < 11 {
return TaggedLoggingMessage{}, fmt.Errorf("tagged logging message too short")
}
return TaggedLoggingMessage{
LogLevel: data[0],
Tag: binary.LittleEndian.Uint16(data[1:3]),
Timestamp: binary.LittleEndian.Uint64(data[3:11]),
Message: string(data[11:]),
}, nil
}