-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathprotocolbuffer_document.go
214 lines (179 loc) · 5.73 KB
/
protocolbuffer_document.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
package xpath
import (
"context"
"encoding/hex"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
path "github.com/antchfx/xpath"
"github.com/bufbuild/protocompile"
"github.com/srebhan/protobufquery"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
"github.com/influxdata/telegraf"
)
type protobufDocument struct {
MessageFiles []string
MessageType string
ImportPaths []string
SkipBytes int64
Log telegraf.Logger
msg *dynamicpb.Message
unmarshaller proto.UnmarshalOptions
}
func (d *protobufDocument) Init() error {
// Check the message definition and type
if len(d.MessageFiles) == 0 {
return errors.New("protocol-buffer files not set")
}
if d.MessageType == "" {
return errors.New("protocol-buffer message-type not set")
}
// Load the file descriptors from the given protocol-buffer definition
ctx := context.Background()
resolver := &protocompile.SourceResolver{ImportPaths: d.ImportPaths}
compiler := &protocompile.Compiler{
Resolver: protocompile.WithStandardImports(resolver),
}
files, err := compiler.Compile(ctx, d.MessageFiles...)
if err != nil {
return fmt.Errorf("parsing protocol-buffer definition failed: %w", err)
}
if len(files) < 1 {
return errors.New("files do not contain a file descriptor")
}
// Register all definitions in the file in the global registry
var registry protoregistry.Files
for _, f := range files {
if err := registry.RegisterFile(f); err != nil {
return fmt.Errorf("adding file %q to registry failed: %w", f.Path(), err)
}
}
d.unmarshaller = proto.UnmarshalOptions{
RecursionLimit: protowire.DefaultRecursionLimit,
Resolver: dynamicpb.NewTypes(®istry),
}
// Lookup given type in the loaded file descriptors
msgFullName := protoreflect.FullName(d.MessageType)
descriptor, err := registry.FindDescriptorByName(msgFullName)
if err != nil {
d.Log.Infof("Could not find %q... Known messages:", msgFullName)
var known []string
registry.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
name := strings.TrimSpace(string(fd.FullName()))
if name != "" {
known = append(known, name)
}
return true
})
sort.Strings(known)
for _, name := range known {
d.Log.Infof(" %s", name)
}
return err
}
// Get a prototypical message for later use
msgDesc, ok := descriptor.(protoreflect.MessageDescriptor)
if !ok {
return fmt.Errorf("%q is not a message descriptor (%T)", msgFullName, descriptor)
}
d.msg = dynamicpb.NewMessage(msgDesc)
if d.msg == nil {
return fmt.Errorf("creating message template for %q failed", msgDesc.FullName())
}
return nil
}
func (d *protobufDocument) Parse(buf []byte) (dataNode, error) {
msg := d.msg.New()
// Unmarshal the received buffer
if err := d.unmarshaller.Unmarshal(buf[d.SkipBytes:], msg.Interface()); err != nil {
hexbuf := hex.EncodeToString(buf)
d.Log.Debugf("raw data (hex): %q (skip %d bytes)", hexbuf, d.SkipBytes)
return nil, err
}
return protobufquery.Parse(msg)
}
func (*protobufDocument) QueryAll(node dataNode, expr string) ([]dataNode, error) {
// If this panics it's a programming error as we changed the document type while processing
native, err := protobufquery.QueryAll(node.(*protobufquery.Node), expr)
if err != nil {
return nil, err
}
nodes := make([]dataNode, 0, len(native))
for _, n := range native {
nodes = append(nodes, n)
}
return nodes, nil
}
func (*protobufDocument) CreateXPathNavigator(node dataNode) path.NodeNavigator {
// If this panics it's a programming error as we changed the document type while processing
return protobufquery.CreateXPathNavigator(node.(*protobufquery.Node))
}
func (d *protobufDocument) GetNodePath(node, relativeTo dataNode, sep string) string {
names := make([]string, 0)
// If these panic it's a programming error as we changed the document type while processing
nativeNode := node.(*protobufquery.Node)
nativeRelativeTo := relativeTo.(*protobufquery.Node)
// Climb up the tree and collect the node names
n := nativeNode.Parent
for n != nil && n != nativeRelativeTo {
kind := reflect.Invalid
if n.Parent != nil && n.Parent.Value() != nil {
kind = reflect.TypeOf(n.Parent.Value()).Kind()
}
switch kind {
case reflect.Slice, reflect.Array:
// Determine the index for array elements
names = append(names, d.index(n))
default:
// Use the name if not an array
names = append(names, n.Name)
}
n = n.Parent
}
if len(names) < 1 {
return ""
}
// Construct the nodes
nodepath := ""
for _, name := range names {
nodepath = name + sep + nodepath
}
return nodepath[:len(nodepath)-1]
}
func (d *protobufDocument) GetNodeName(node dataNode, sep string, withParent bool) string {
// If this panics it's a programming error as we changed the document type while processing
nativeNode := node.(*protobufquery.Node)
name := nativeNode.Name
// Check if the node is part of an array. If so, determine the index and
// concatenate the parent name and the index.
kind := reflect.Invalid
if nativeNode.Parent != nil && nativeNode.Parent.Value() != nil {
kind = reflect.TypeOf(nativeNode.Parent.Value()).Kind()
}
switch kind {
case reflect.Slice, reflect.Array:
if name == "" && nativeNode.Parent != nil && withParent {
name = nativeNode.Parent.Name + sep
}
return name + d.index(nativeNode)
}
return name
}
func (*protobufDocument) OutputXML(node dataNode) string {
native := node.(*protobufquery.Node)
return native.OutputXML()
}
func (*protobufDocument) index(node *protobufquery.Node) string {
idx := 0
for n := node; n.PrevSibling != nil; n = n.PrevSibling {
idx++
}
return strconv.Itoa(idx)
}