forked from CiscoDevNet/bigmuddy-network-telemetry-pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec_gpb.go
1381 lines (1197 loc) · 34 KB
/
codec_gpb.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
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// February 2016, cisco
//
// Copyright (c) 2016 by cisco Systems, Inc.
// All rights reserved.
//
//
// Provide GPB (compact and K/V) encode/decode services.
//
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
log "github.com/Sirupsen/logrus"
telem "github.com/cisco/bigmuddy-network-telemetry-proto/proto_go"
pdt "github.com/cisco/bigmuddy-network-telemetry-proto/proto_go/old/telemetry"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"reflect"
"regexp"
"strings"
"sync"
"sync/atomic"
"text/template"
)
const (
GPBCODEC = "GPBCodec"
CODEC_GPB_PIPELINE_EDIT_SUFFIX = "_PIPELINE_EDIT"
CODEC_GPB_PREALLOC_PDT_ROWS = 32
)
type dataMsgGPB struct {
original []byte
source msgproducer
//
// Top level cached decode.
cachedDecode *telem.Telemetry
//
// Decoded tbl; applicable only to GPB. For GPBK/V, the top level
// decode completes the effort. Note that we use atomic.Value for
// the cache type, with true type of *gpbDecodeTbl. This type is
// set once, and once it is, then it is never reset. We only lock
// while we're building to avoid unnecessarily decoding multiple
// concurrent time, not for protection (note we use atomic
// load/store).
cachedDecodeTbl atomic.Value
cachedDecodeTblLock sync.Mutex
}
//
// Track
type gpbDecodeTbl struct {
rows []*gpbDecodeRow
}
type gpbDecodeRow struct {
Timestamp uint64
Keys proto.Message
Content proto.Message
}
func (m *dataMsgGPB) getDataMsgStreamType() dataMsgStreamType {
return dMStreamGPB
}
func (m *dataMsgGPB) getMetaDataPath() (error, string) {
return nil, m.cachedDecode.EncodingPath
}
func (m *dataMsgGPB) getMetaDataIdentifier() (error, string) {
return nil, m.source.String()
}
func (m *dataMsgGPB) getMetaData() *dataMsgMetaData {
return &dataMsgMetaData{
Path: m.cachedDecode.EncodingPath,
Identifier: m.source.String(),
}
}
func (m *dataMsgGPB) getDataMsgDescription() string {
var node_id string
_, source := m.getMetaDataIdentifier()
if m.cachedDecode != nil {
node_id = m.cachedDecode.GetNodeIdStr()
} else {
node_id = "n/a"
}
_, path := m.getMetaDataPath()
return fmt.Sprintf("GPB(common) Message [%s(%s)/%s msg len: %d]",
source, node_id, path, len(m.original))
}
func (p *codecGPB) dataMsgToBlock(dM dataMsg) (error, []byte) {
return fmt.Errorf("CODEC GPB: only decoding is supported currently"),
nil
}
//
// Support function to extract the value field from K/V Field.
func extractGPBKVNativeTypeFromOneof(
field *telem.TelemetryField,
must_be_numeric bool) interface{} {
switch field.ValueByType.(type) {
case *telem.TelemetryField_BytesValue:
if !must_be_numeric {
return field.GetBytesValue()
}
case *telem.TelemetryField_StringValue:
if !must_be_numeric {
return field.GetStringValue()
}
case *telem.TelemetryField_BoolValue:
if !must_be_numeric {
return field.GetBoolValue()
}
case *telem.TelemetryField_Uint32Value:
return field.GetUint32Value()
case *telem.TelemetryField_Uint64Value:
return field.GetUint64Value()
case *telem.TelemetryField_Sint32Value:
return field.GetSint32Value()
case *telem.TelemetryField_Sint64Value:
return field.GetSint64Value()
case *telem.TelemetryField_DoubleValue:
return field.GetDoubleValue()
case *telem.TelemetryField_FloatValue:
return field.GetFloatValue()
}
return nil
}
func telemetryKvToSockDrawer(item []*telem.TelemetryField) *sockDrawer {
var s sockDrawer
if item == nil || len(item) == 0 {
return nil
}
s = make(sockDrawer, 30) // Hint, of the number of fields
placeInArrayMap := map[string]bool{}
for _, field := range item {
var fieldVal interface{}
var hint int
//
// Strictly speaking we should assert that no field name passed in
// has CODEC_GPB_PIPELINE_EDIT_SUFFIX to avoid possibly mistaking
// it for one of ours
existing_entry, exists := s[field.Name]
_, placeInArray := placeInArrayMap[field.Name]
children := field.GetFields()
if children == nil {
fieldVal = extractGPBKVNativeTypeFromOneof(field, false)
hint = 10
} else {
fieldVal = telemetryKvToSockDrawer(children)
hint = len(children)
}
if !placeInArray && !exists {
//
// this is the common case by far!
s[field.Name] = fieldVal
} else {
newName := field.Name + CODEC_GPB_PIPELINE_EDIT_SUFFIX
if exists {
//
// Play safe. If entry exists, placeInArray should be
// false, because once placeInArray becomes true, the
// s[field.Name] will NOT be populated.
if !placeInArray {
// Create list
s[newName] = make([]interface{}, 0, hint)
// Remember that this field name is arrayified(!?)
placeInArrayMap[field.Name] = true
// Add existing entry to new array)
s[newName] = append(s[newName].([]interface{}),
existing_entry)
// Delete existing entry from old
delete(s, field.Name)
placeInArray = true
} else {
log.WithFields(log.Fields{
"FieldName": field.Name,
}).Error(
"GPB KV inconsistency, processing repeated field names")
}
}
if placeInArray && fieldVal != nil {
s[newName] = append(s[newName].([]interface{}), fieldVal)
}
}
}
return &s
}
//
// Anything goes in a sockDrawer. This is a name-to-opaque map
// container where we collect content before marshalling into JSON or
// filtering in template, without necessarily knowing the content
// type.
type sockDrawer map[string]interface{}
type rowToFilter struct {
Timestamp uint64
Keys interface{}
Content interface{}
}
type msgToFilter struct {
Node_id string
Encoding_path string
Subscription string
collection_id uint64
collection_start_time uint64
collection_end_time uint64
Msg_timestamp uint64
Data []rowToFilter
}
func (m *msgToFilter) populateDataFromGPB(s *telem.Telemetry) error {
m.Node_id = s.GetNodeIdStr()
m.Subscription = s.GetSubscriptionIdStr()
m.Encoding_path = s.EncodingPath
m.collection_id = s.CollectionId
m.collection_start_time = s.CollectionStartTime
m.collection_end_time = s.CollectionEndTime
m.Msg_timestamp = s.MsgTimestamp
compactGPBTable := s.GetDataGpb()
if compactGPBTable != nil {
//
// native gpb support to follow
return fmt.Errorf("No support for native gpb msgToFilter")
} else {
//
// We need to unk/v the content before we JSONify.
topfields := s.GetDataGpbkv()
m.Data = make([]rowToFilter, len(topfields))
i := 0
for _, topfield := range topfields {
rtf := &m.Data[i]
i++
rtf.Timestamp = topfield.Timestamp
for _, kcfield := range topfield.GetFields() {
// We should be iterating over two fields at this
//level; keys and content.
fields := kcfield.GetFields()
if len(fields) > 0 {
if kcfield.Name == "keys" {
rtf.Keys = telemetryKvToSockDrawer(fields)
} else if kcfield.Name == "content" {
rtf.Content = telemetryKvToSockDrawer(fields)
}
} else {
return fmt.Errorf("message with no row, nothing to filter")
}
}
}
}
return nil
}
//
// Message row type used for serialisation
type rowToSerialise struct {
Timestamp uint64
Keys *json.RawMessage
Content *json.RawMessage
}
//
// Message type (including header and rows) used for serialisation
type msgToSerialise struct {
Source string
Telemetry *json.RawMessage
Rows []*rowToSerialise `json:"Rows,omitempty"`
}
//
// Produce byte stream from GPB K/V encoded content in preparation for
// JSON events. Eventually, we should cache the decoded content to
// avoid multiple output stages having to decode original multeiple
// times. This is easy, but will require locking access to data
// message cache.
//
// Much as with codecGPBJSONifyDataGPBKV, we ought to cache the
// sockDrawer before we JSONify. We will do this when/if we add
// template based transformation of content.
func codecGPBJSONifyDataGPBKV(m *dataMsgGPB, s *msgToSerialise) {
skipKeys := 0
skipContent := 0
empty := 0
for _, topfield := range m.cachedDecode.GetDataGpbkv() {
//
// Extract timestamp at this level
var rts rowToSerialise
// At this level we may have a populated timestamp and fields
// leading to key/value
rts.Timestamp = topfield.Timestamp
for _, kcfield := range topfield.GetFields() {
// We should be iterating over two fields at this level;
// keys and content.
//
fields := kcfield.GetFields()
if len(fields) > 0 {
if kcfield.Name == "keys" {
sKeys, err := json.Marshal(telemetryKvToSockDrawer(fields))
if err == nil {
keys := json.RawMessage(sKeys)
rts.Keys = &keys
} else {
skipKeys++
}
} else if kcfield.Name == "content" {
sContent, err := json.Marshal(telemetryKvToSockDrawer(fields))
if err == nil {
content := json.RawMessage(sContent)
rts.Content = &content
} else {
skipContent++
}
} else {
empty++
}
}
}
s.Rows = append(s.Rows, &rts)
}
if skipKeys > 0 || skipContent > 0 {
codecMetaMonitor.BasePathDecodeError.WithLabelValues(
GPBCODEC, m.source.String(), m.cachedDecode.EncodingPath,
"partial decode").Inc()
}
}
//
// Produce byte stream from compact GPB encoded content.
func codecGPBJSONifyDataGPB(
m *dataMsgGPB, s *msgToSerialise) {
skipKeys := 0
skipContent := 0
marshaller := &jsonpb.Marshaler{
//
// EmitUInt64Unquoted ensures that gpb int64/uint64 fields are
// marshalled unstringified.
//
// jsonpb marshals int64,uint64 to string by default.
// https://github.com/golang/protobuf/issues/211
// https://tools.ietf.org/html/rfc7159#section-6
// http://stackoverflow.com/questions/16946306/preserve-int64-values-when-parsing-json-in-go
//
// Paraphrased: while controversial, it is deemed safer to use
// string encoding for u/int64 to make sure that
// implementations using IEEE574 for numbers do not go wrong
// on numbers outside the 53 bits of integer precision they
// support. Hence their choice for 64 bit being a string in
// the mapping.
//
// While we control consumers (e.g. no js consumers), we will
// marshal to numbers, so unmarshalling on the other side can
// be results in a comparable numeric without special case
// coercion.
//
// If compilation fails because EmitUInt64Unquoted is not an
// attribute of jsonpb.Marshaller, it probably means that the
// vendored protobuf package was updated and 'go generate' was
// not rerun to patch in vendor.patch.
//
EmitUInt64Unquoted: true,
EmitDefaults: true,
OrigName: true,
}
//
// Fetch of decode and cache deep decode of GPB content.
tbl := m.getGPBDecodedTbl()
if tbl == nil {
// No mapping available... just track base64 encoded hex.
compactGPBTable := m.cachedDecode.GetDataGpb()
if compactGPBTable == nil {
return
}
rows := compactGPBTable.GetRow()
if rows == nil {
return
}
for _, row := range rows {
var rts rowToSerialise
rts.Timestamp = row.Timestamp
if len(row.Keys) > 0 {
decodedKeysJSON, err := json.Marshal(
map[string]string{
"hexdump": base64.StdEncoding.EncodeToString(row.Keys)})
if err == nil {
keys := json.RawMessage(decodedKeysJSON)
rts.Keys = &keys
} else {
skipKeys++
}
}
if len(row.Content) > 0 {
decodedContentJSON, err := json.Marshal(
map[string]string{
"hexdump": base64.StdEncoding.EncodeToString(row.Content)})
if err == nil {
content := json.RawMessage(decodedContentJSON)
rts.Content = &content
} else {
skipContent++
}
}
s.Rows = append(s.Rows, &rts)
}
} else {
for _, row := range tbl.rows {
var rts rowToSerialise
rts.Timestamp = row.Timestamp
decodedContentJSON, err := marshaller.MarshalToString(row.Content)
if err != nil {
skipContent++
} else {
content := json.RawMessage(decodedContentJSON)
rts.Content = &content
}
decodedKeysJSON, err := marshaller.MarshalToString(row.Keys)
if err != nil {
skipKeys++
} else {
keys := json.RawMessage(decodedKeysJSON)
rts.Keys = &keys
}
s.Rows = append(s.Rows, &rts)
}
}
if skipKeys > 0 || skipContent > 0 {
codecMetaMonitor.BasePathDecodeError.WithLabelValues(
GPBCODEC, m.source.String(), m.cachedDecode.EncodingPath,
"partial decode").Inc()
}
}
//
// This function is capable of producing streams for GPB (passed
//through from input), JSON and JSON events from GPB. GPB in this
//context means GPB K/V or compact encoded using the common header.
func (m *dataMsgGPB) produceByteStream(
streamSpec *dataMsgStreamSpec) (error, []byte) {
switch streamSpec.streamType {
case dMStreamGPB, dMStreamMsgDefault:
// Simply return the original encoded message
return nil, m.original
case dMStreamTemplate:
var b bytes.Buffer
var msg msgToFilter
msg.populateDataFromGPB(m.cachedDecode)
if streamSpec.context != nil {
parsedTemplate := streamSpec.context.(*template.Template)
err := parsedTemplate.Execute(&b, msg)
return err, b.Bytes()
}
return fmt.Errorf("GPB CODEC: parsed template missing"), nil
case dMStreamJSONEvents, dMStreamJSON:
var copy telem.Telemetry
marshaller := &jsonpb.Marshaler{
// See long comments above EmitUInt64Unquoted, eslewhere
// in this file.
EmitUInt64Unquoted: true,
EmitDefaults: true,
OrigName: true}
var s msgToSerialise
copy = *m.cachedDecode
// Remarshal the decoded content to JSON
compactGPBTable := m.cachedDecode.GetDataGpb()
if compactGPBTable != nil {
// If we have compact GPB table with rows, we need to decode
// further.
codecGPBJSONifyDataGPB(m, &s)
copy.DataGpb = nil
} else {
//
// We need to unk/v the content before we JSONify.
codecGPBJSONifyDataGPBKV(m, &s)
copy.DataGpbkv = nil
}
telemetryJSON, err := marshaller.MarshalToString(©)
if err != nil {
return err, nil
}
telemetryJSONRaw := json.RawMessage(telemetryJSON)
s.Telemetry = &telemetryJSONRaw
//
// Track the source as picked off the wire.
s.Source = m.source.String()
//
// Finally serialise
if streamSpec.streamType == dMStreamJSONEvents {
if len(s.Rows) == 0 {
//
// Nothing to generate. This typically happens when a
// message is received with collection end time and
// nothing else.
return nil, nil
}
//
// In this case we are producing a JSON array of events, where
// each event carries header information with it. This makes consumption
// in third party consumers easier in some cases.
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)
buffer.WriteString("[")
first := true
type msgToSerialise2 struct {
Source string
Telemetry *json.RawMessage
Row *rowToSerialise `json:"Rows,omitempty"`
}
var r msgToSerialise2
r.Source = s.Source
r.Telemetry = s.Telemetry
for _, row := range s.Rows {
if first {
first = false
} else {
buffer.WriteString(",")
}
r.Row = row
err := encoder.Encode(r)
if err != nil {
return fmt.Errorf("Marshalling collected event content, [%+v][%+v]",
r, err), nil
}
}
buffer.WriteString("]")
return nil, buffer.Bytes()
} else {
//
// Serialise the whole batch as it is produced.
b, err := json.Marshal(s)
if err != nil {
return fmt.Errorf("Marshalling collected content, [%+v][%+v]",
s, err), nil
}
return err, b
}
}
return fmt.Errorf("GPB CODEC: reformat GPB msg to [%s] is"+
" not supported", dataMsgStreamTypeString(streamSpec.streamType)), nil
}
func (m *dataMsgGPB) produceGPBKVMetricsForNode(
spec *metricsSpec,
node *metricsSpecNode,
fields []*telem.TelemetryField,
timestamp uint64,
tags []metricsAtom,
outputHandler metricsOutputHandler,
buf metricsOutputContext) {
var ts uint64
var val interface{}
var written bool
//
// We run multiple times through a given level.
// - first pass we extract tags,
// - second pass we extract sensors,
// - third pass we recurse down into children.
//
// We exploit the fact that at least at the top level, tags are
// highly likely to be at the beginning.
//
// Alternative would have required us to collect all sensors in
// the pass before writing them out to make sure that tags are all
// present.
//
fieldsMap := node.fieldsMapsByType[metricsSpecNodeTypeTag]
collected := 0
tagsTarget := len(fieldsMap)
if tagsTarget > 0 {
for _, field := range fields {
child, ok := fieldsMap[field.Name]
if !ok {
continue
}
val = extractGPBKVNativeTypeFromOneof(field, false)
if val != nil {
tags = append(tags, metricsAtom{
key: child.fqName,
val: val,
})
}
collected++
if collected >= tagsTarget {
break
}
}
}
fieldsMap = node.fieldsMapsByType[metricsSpecNodeTypeSensor]
sensorTarget := len(fieldsMap)
if sensorTarget != 0 {
for _, field := range fields {
child, ok := fieldsMap[field.Name]
if !ok {
continue
}
//
// Choose timestamp to pass to writer
if field.Timestamp == 0 {
ts = timestamp
} else {
ts = field.Timestamp
}
if child.Track {
buf := new(bytes.Buffer)
buf.WriteString(child.fqName)
for i := 0; i < len(tags); i++ {
buf.WriteString(
fmt.Sprintf(
" %s=\"%v\"",
tags[i].key,
tags[i].val))
}
//
// We're tracking stats for this one...
spec.stats.statRecordUpdate(buf.String(), ts)
}
val = extractGPBKVNativeTypeFromOneof(field, false)
if val != nil {
outputHandler.buildMetric(
tags,
metricsAtom{
key: child.fqName,
val: val,
},
ts,
buf)
written = true
}
//
// We cannot break early here in order to be able to
// support leaf lists. i.e. multiple repeated instances of
// the same name
}
}
if written {
outputHandler.flushMetric(tags, ts, buf)
}
fieldsMap = node.fieldsMapsByType[metricsSpecNodeTypeContainer]
containerTarget := len(fieldsMap)
if containerTarget != 0 {
for _, field := range fields {
child, ok := fieldsMap[field.Name]
if !ok {
continue
}
//
// Choose the more precise timestamp to carry down
if field.Timestamp == 0 {
ts = timestamp
} else {
ts = field.Timestamp
}
m.produceGPBKVMetricsForNode(
spec,
child,
field.GetFields(),
ts,
tags,
outputHandler,
buf)
//
// We cannot break early here since the collection of
// fields may well be of the same type, like when we are
// mapping a yang list.
}
}
}
func (m *dataMsgGPB) produceGPBKVMetrics(
spec *metricsSpec,
node *metricsSpecNode,
outputHandler metricsOutputHandler,
tags []metricsAtom,
buf metricsOutputContext) error {
var timestamp uint64
for _, topField := range m.cachedDecode.GetDataGpbkv() {
if topField.Timestamp != 0 {
timestamp = topField.Timestamp
} else {
timestamp = m.cachedDecode.MsgTimestamp
}
tagsCopy := tags
for _, kcfield := range topField.GetFields() {
//
// We should be iterating over two fields at this level;
// keys and content. Automatically add keys to tags. We
// rely on the order, keys first, than content. We could
// make this more robust and break dependency.
if kcfield.Name == "keys" {
for _, key := range kcfield.GetFields() {
tagsCopy = append(tagsCopy, metricsAtom{
key: outputHandler.adaptTagName(key.Name),
val: extractGPBKVNativeTypeFromOneof(key, false),
})
}
}
if kcfield.Name == "content" {
m.produceGPBKVMetricsForNode(
spec,
node,
kcfield.GetFields(),
timestamp,
tagsCopy,
outputHandler,
buf)
}
}
}
return nil
}
//
// getGPBDecodedTbl returns the cached decoded table. If the content
// has not been decoded yet, content is decoded and cached too.
func (m *dataMsgGPB) getGPBDecodedTbl() *gpbDecodeTbl {
tblVal := m.cachedDecodeTbl.Load()
if tblVal == nil {
//
// if shallow decode is missing, nothing doing
compactGPBTable := m.cachedDecode.GetDataGpb()
if compactGPBTable == nil {
//
// Legit e.g. when sending just the header with end of
// collection.
return nil
}
//
// We will build and then set the cached value. Note that,
// while we're decoding, others might and we may end up
// replacing the cached value.
m.cachedDecodeTblLock.Lock()
defer m.cachedDecodeTblLock.Unlock()
tblVal = m.cachedDecodeTbl.Load()
if tblVal == nil {
mapping := telem.EncodingPathToMessageReflectionSet(
&telem.ProtoKey{
EncodingPath: m.cachedDecode.EncodingPath,
Version: ""})
if mapping == nil {
codecMetaMonitor.BasePathDecodeError.WithLabelValues(
GPBCODEC, m.source.String(), m.cachedDecode.EncodingPath,
"proto archive does not support path/version").Inc()
return nil
}
skipKeys := 0
skipContent := 0
rows := compactGPBTable.GetRow()
cachedTbl := &gpbDecodeTbl{
rows: make([]*gpbDecodeRow, 0, len(rows)),
}
for _, row := range rows {
var decodedKeysMsg proto.Message
var decodedContentMsg proto.Message
srowContentType := mapping.MessageReflection(
telem.PROTO_CONTENT_MSG)
contentType := srowContentType.Elem()
decodedContent := reflect.New(contentType)
decodedContentMsg =
decodedContent.Interface().(proto.Message)
err := proto.Unmarshal(row.Content, decodedContentMsg)
if err != nil {
skipContent++
}
srowKeysType := mapping.MessageReflection(
telem.PROTO_KEYS_MSG)
if srowKeysType != nil {
keysType := srowKeysType.Elem()
decodedKeys := reflect.New(keysType)
decodedKeysMsg =
decodedKeys.Interface().(proto.Message)
err = proto.Unmarshal(row.Keys, decodedKeysMsg)
if err != nil {
skipKeys++
}
}
cachedTbl.rows = append(cachedTbl.rows, &gpbDecodeRow{
Timestamp: row.Timestamp,
Keys: decodedKeysMsg,
Content: decodedContentMsg,
})
}
//
// Cache value
m.cachedDecodeTbl.Store(cachedTbl)
if skipKeys > 0 || skipContent > 0 {
codecMetaMonitor.BasePathDecodeError.WithLabelValues(
GPBCODEC, m.source.String(), m.cachedDecode.EncodingPath,
"partial decode").Inc()
}
//
// Reload cached content
tblVal = m.cachedDecodeTbl.Load()
}
}
if tblVal != nil {
return tblVal.(*gpbDecodeTbl)
}
return nil
}
// Compile regex for extracting field names from protobuf tag struct
// just the once. A Regexp is safe for concurrent use by multiple
// goroutines.
var codecGPBFieldNameParser = regexp.MustCompile("name=(.*?)(,json|$)")
var codecGPBFieldNameGroup = 1
//
// codecGPBExtractFieldName takes a field value from a type, and
// extracts name from protobuf tag.
func codecGPBExtractFieldName(ft reflect.StructField) string {
pbt, ok := ft.Tag.Lookup("protobuf")
if !ok {
return ft.Name
}
matchgroup := codecGPBFieldNameParser.FindStringSubmatch(pbt)
if matchgroup == nil {
return ft.Name
}
if len(matchgroup) < codecGPBFieldNameGroup+1 {
return ft.Name
}
return matchgroup[codecGPBFieldNameGroup]
}
func (m *dataMsgGPB) produceGPBMetricsForNode(
spec *metricsSpec,
node *metricsSpecNode,
refv reflect.Value,
timestamp uint64,
tags []metricsAtom,
outputHandler metricsOutputHandler,
buf metricsOutputContext) {
var written bool
if refv.Kind() != reflect.Struct {
return
}
intNamesCached := node.internalNamesCached[dMStreamGPB].Load().(bool)
if !intNamesCached {
node.internalNamesCachedLock.Lock()
//
// Check if cache has been loaded between when we checked and
// when we locked. If it has we're done.
intNamesCached = node.internalNamesCached[dMStreamGPB].Load().(bool)
if !intNamesCached {
reftyp := refv.Type()
for i := 0; i < refv.NumField(); i++ {
fldtype := reftyp.Field(i)
extName := codecGPBExtractFieldName(fldtype)
childNode, ok := node.fieldsMap[extName]
if ok {
childNode.internalName[dMStreamGPB] = fldtype.Name
}
}
node.internalNamesCached[dMStreamGPB].Store(true)
}
node.internalNamesCachedLock.Unlock()
}
//
// Do tag leaves at this level. Because the json name is not the
// same as protobuf name, spec must account for this. This will
// need to be fixed by fixing up the mapping type when building
// the spec.
fieldsMap := node.fieldsMapsByType[metricsSpecNodeTypeTag]
for fieldName, node := range fieldsMap {
//
// We only ever get here when internal names have been cached,
// and once cached, internal names are never updated so we
// don't need to take a lock.
intName := node.internalName[dMStreamGPB]
if intName == "" {
intName = fieldName
}
fval := refv.FieldByName(intName)
if !fval.IsValid() {
//
// Spec mismatch for a field?
countErr := fmt.Sprintf("metric extract tag %s %s", node.fqName,
fieldName)
codecMetaMonitor.BasePathDecodeError.WithLabelValues(
GPBCODEC, m.source.String(), m.cachedDecode.EncodingPath,
countErr).Inc()
continue
}
tagname := outputHandler.adaptTagName(fieldName)
tags = append(tags, metricsAtom{
key: tagname, val: fval,
})
}