forked from google/gnxi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gnmi_subscribe.go
283 lines (254 loc) · 8.43 KB
/
gnmi_subscribe.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
/* Copyright 2020 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
log "github.com/golang/glog"
"github.com/golang/protobuf/proto"
"github.com/google/gnxi/utils/credentials"
"github.com/google/gnxi/utils/xpath"
"github.com/openconfig/gnmi/proto/gnmi"
pb "github.com/openconfig/gnmi/proto/gnmi"
"google.golang.org/grpc"
)
type arrayFlags []string
func (i *arrayFlags) String() string {
return ""
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
var (
xPathFlags arrayFlags
pbPathFlags arrayFlags
targetAddr = flag.String("target_addr", ":9339", "The target address in the format of host:port")
connectionTimeout = flag.Duration("timeout", 0, "The timeout for a request in seconds, 0 seconds by default (no timeout), e.g 10s")
subscriptionOnce = flag.Bool("once", false, "If true, the target sends values once off")
subscriptionPoll = flag.Bool("poll", false, "If true, the target sends values on request")
streamOnChange = flag.Bool("stream_on_change", false, "If true, the target sends updates on change")
sampleInterval = flag.Uint64("sample_interval", 0, "If defined, the target sends sample values according to this interval in nano seconds")
encodingFormat = flag.String("encoding", "JSON_IETF", "The encoding format used by the target for notifications")
suppressRedundant = flag.Bool("suppress_redundant", false, "If true, in SAMPLE mode, unchanged values are not sent by the target")
heartbeatInterval = flag.Uint64("heartbeat_interval", 0, "Specifies maximum allowed period of silence in seconds when surpress redundant is used")
updatesOnly = flag.Bool("updates_only", false, "If true, the target only transmits updates to the subscribed paths")
)
func main() {
flag.Var(&xPathFlags, "xpath", "xpath of the config node to be fetched")
flag.Var(&pbPathFlags, "pbpath", "protobuf format path of the config node to be fetched")
flag.Set("logtostderr", "true")
flag.Parse()
opts := credentials.ClientCredentials()
conn, err := grpc.Dial(*targetAddr, opts...)
if err != nil {
log.Fatalf("Dialing to %s failed: %v", *targetAddr, err)
}
defer conn.Close()
client := pb.NewGNMIClient(conn)
ctx := context.Background()
if *connectionTimeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, *connectionTimeout)
defer cancel()
}
subscribeClient, err := client.Subscribe(ctx)
if err != nil {
log.Fatalf("Error creating GNMI_SubscribeClient: %v", err)
}
encoding, err := parseEncoding(*encodingFormat)
if err != nil {
log.Exitf("Error parsing encoding: %v", err)
}
subscriptionListMode, err := subscriptionMode(*subscriptionPoll, *subscriptionOnce)
if err != nil {
flag.Usage()
log.Exit(err)
}
pbPathList, err := parsePaths(xPathFlags, pbPathFlags)
if err != nil {
log.Exitf("Error parsing paths: %v", err)
}
subscriptions, err := assembleSubscriptions(*streamOnChange, *sampleInterval, pbPathList)
if err != nil {
log.Exitf("Error assembling subscriptions: %v", err)
}
request := &pb.SubscribeRequest{
Request: &pb.SubscribeRequest_Subscribe{
Subscribe: &pb.SubscriptionList{
Encoding: encoding,
Mode: subscriptionListMode,
Subscription: subscriptions,
UpdatesOnly: *updatesOnly,
},
},
}
log.V(1).Info("SubscribeRequest:\n", proto.MarshalTextString(request))
if err := subscribeClient.Send(request); err != nil {
log.Exitf("Failed to send request: %v", err)
}
switch subscriptionListMode {
case pb.SubscriptionList_STREAM:
if err := stream(subscribeClient); err != nil {
log.Exitf("Error using STREAM mode: %v", err)
}
case pb.SubscriptionList_POLL:
if err := poll(subscribeClient, *updatesOnly, pollUser); err != nil {
log.Exitf("Error using POLL mode: %v", err)
}
case pb.SubscriptionList_ONCE:
if err := once(subscribeClient); err != nil {
log.Exitf("Error using ONCE mode: %v", err)
}
}
}
func pollUser() {
log.Info("Press enter to poll")
fmt.Scanln()
}
func stream(subscribeClient gnmi.GNMI_SubscribeClient) error {
for {
if closed, err := receiveNotifications(subscribeClient); err != nil {
return err
} else if closed {
return nil
}
}
}
func poll(subscribeClient gnmi.GNMI_SubscribeClient, updatesOnly bool, pollInput func()) error {
ready := make(chan bool, 1)
ready <- true
pollRequest := &pb.SubscribeRequest{Request: &pb.SubscribeRequest_Poll{}}
if updatesOnly {
res, err := subscribeClient.Recv()
if err != nil {
return err
}
if syncRes := res.GetSyncResponse(); !syncRes {
return errors.New("-updates_only flag is set but failed to receive SyncResponse first for POLL mode")
}
log.Info("SyncResponse received")
}
for {
select {
case <-ready:
pollInput()
if err := subscribeClient.Send(pollRequest); err != nil {
return err
}
log.V(1).Info("SubscribeRequest:\n", proto.MarshalTextString(pollRequest))
default:
if closed, err := receiveNotifications(subscribeClient); err != nil {
return err
} else if closed {
return nil
}
ready <- true
}
}
}
func once(subscribeClient gnmi.GNMI_SubscribeClient) error {
if _, err := receiveNotifications(subscribeClient); err != nil {
return err
}
return nil
}
func receiveNotifications(subscribeClient gnmi.GNMI_SubscribeClient) (bool, error) {
for {
res, err := subscribeClient.Recv()
if err == io.EOF {
return true, nil
}
if err != nil {
return false, err
}
switch res.Response.(type) {
case *pb.SubscribeResponse_SyncResponse:
log.Info("SyncResponse received")
return false, nil
case *pb.SubscribeResponse_Update:
fmt.Println("==>\n", proto.MarshalTextString(res))
default:
return false, errors.New("unexpected response type")
}
}
}
func assembleSubscriptions(streamOnChange bool, sampleInterval uint64, paths []*pb.Path) ([]*pb.Subscription, error) {
var subscriptions []*pb.Subscription
var subscriptionMode gnmi.SubscriptionMode
switch {
case streamOnChange && sampleInterval != 0:
return nil, errors.New("only one of -stream_on_change and -sample_interval can be set")
case streamOnChange:
subscriptionMode = pb.SubscriptionMode_ON_CHANGE
case sampleInterval != 0:
subscriptionMode = pb.SubscriptionMode_SAMPLE
default:
subscriptionMode = pb.SubscriptionMode_TARGET_DEFINED
}
for _, path := range paths {
subscription := &pb.Subscription{
Path: path,
Mode: subscriptionMode,
SampleInterval: sampleInterval,
SuppressRedundant: *suppressRedundant,
HeartbeatInterval: *heartbeatInterval,
}
subscriptions = append(subscriptions, subscription)
}
return subscriptions, nil
}
func subscriptionMode(subscriptionPoll, subscriptionOnce bool) (gnmi.SubscriptionList_Mode, error) {
switch {
case subscriptionPoll && subscriptionOnce:
return 0, errors.New("only one of -once and -poll can be set")
case subscriptionOnce:
return pb.SubscriptionList_ONCE, nil
case subscriptionPoll:
return pb.SubscriptionList_POLL, nil
default:
return pb.SubscriptionList_STREAM, nil
}
}
func parsePaths(xPathFlags, pbPathFlags arrayFlags) ([]*pb.Path, error) {
var pbPathList []*pb.Path
for _, xPath := range xPathFlags {
pbPath, err := xpath.ToGNMIPath(xPath)
if err != nil {
return nil, fmt.Errorf("error in parsing xpath %q to gnmi path", xPath)
}
pbPathList = append(pbPathList, pbPath)
}
for _, textPbPath := range pbPathFlags {
var pbPath pb.Path
if err := proto.UnmarshalText(textPbPath, &pbPath); err != nil {
return nil, fmt.Errorf("error in unmarshaling %q to gnmi Path", textPbPath)
}
pbPathList = append(pbPathList, &pbPath)
}
return pbPathList, nil
}
func parseEncoding(encodingFormat string) (gnmi.Encoding, error) {
encoding, ok := pb.Encoding_value[encodingFormat]
if !ok {
var encodingList []string
for _, name := range pb.Encoding_name {
encodingList = append(encodingList, name)
}
return 0, errors.New("supported encodings: " + strings.Join(encodingList, ", "))
}
return pb.Encoding(encoding), nil
}