-
Notifications
You must be signed in to change notification settings - Fork 50
/
gnmi_server.go
245 lines (222 loc) · 5.98 KB
/
gnmi_server.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
/*
Copyright 2017 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
http://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.
*/
// This gNMI server implementation is based on the one found here:
// https://github.com/openconfig/gnmi/blob/c69a5df04b5329d70e3e76afa773669527cfad9b/subscribe/subscribe.go
package gnmi_output
import (
"errors"
"io"
"log"
"sync"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"github.com/openconfig/gnmi/cache"
"github.com/openconfig/gnmi/coalesce"
"github.com/openconfig/gnmi/ctree"
"github.com/openconfig/gnmi/match"
"github.com/openconfig/gnmi/path"
"github.com/openconfig/gnmi/proto/gnmi"
"github.com/openconfig/gnmi/subscribe"
"github.com/openconfig/gnmic/pkg/api/types"
)
type streamClient struct {
target string
req *gnmi.SubscribeRequest
queue *coalesce.Queue
stream gnmi.GNMI_SubscribeServer
errChan chan<- error
}
type server struct {
gnmi.UnimplementedGNMIServer
//
l *log.Logger
c *cache.Cache
m *match.Match
subscribeRPCsem *semaphore.Weighted
unaryRPCsem *semaphore.Weighted
//
mu *sync.RWMutex
targets map[string]*types.TargetConfig
}
type matchClient struct {
queue *coalesce.Queue
err error
}
type syncMarker struct{}
type resp struct {
stream gnmi.GNMI_SubscribeServer
n *ctree.Leaf
dup uint32
}
func (m *matchClient) Update(n interface{}) {
if m.err != nil {
return
}
_, m.err = m.queue.Insert(n)
}
func (g *gNMIOutput) newServer() *server {
return &server{
l: g.logger,
c: g.c,
m: match.New(),
mu: new(sync.RWMutex),
targets: make(map[string]*types.TargetConfig),
}
}
func (s *server) Update(n *ctree.Leaf) {
switch v := n.Value().(type) {
case *gnmi.Notification:
subscribe.UpdateNotification(s.m, n, v, path.ToStrings(v.Prefix, true))
default:
s.l.Printf("unexpected update type: %T", v)
}
}
func addSubscription(m *match.Match, s *gnmi.SubscriptionList, c *matchClient) func() {
removes := make([]func(), 0, len(s.GetSubscription()))
prefix := path.ToStrings(s.GetPrefix(), true)
for _, p := range s.GetSubscription() {
if p.GetPath() == nil {
continue
}
path := append(prefix, path.ToStrings(p.GetPath(), false)...)
removes = append(removes, m.AddQuery(path, c))
}
return func() {
for _, remove := range removes {
remove()
}
}
}
func (s *server) handleSubscriptionRequest(sc *streamClient) {
var err error
s.l.Printf("processing subscription to target %q", sc.target)
defer func() {
if err != nil {
s.l.Printf("error processing subscription to target %q: %v", sc.target, err)
sc.queue.Close()
sc.errChan <- err
return
}
s.l.Printf("subscription request to target %q processed", sc.target)
}()
if !sc.req.GetSubscribe().GetUpdatesOnly() {
for _, sub := range sc.req.GetSubscribe().GetSubscription() {
var fp []string
fp, err = path.CompletePath(sc.req.GetSubscribe().GetPrefix(), sub.GetPath())
if err != nil {
return
}
err = s.c.Query(sc.target, fp,
func(_ []string, l *ctree.Leaf, _ interface{}) error {
if err != nil {
return err
}
_, err = sc.queue.Insert(l)
return nil
})
if err != nil {
s.l.Printf("target %q failed internal cache query: %v", sc.target, err)
return
}
}
}
_, err = sc.queue.Insert(syncMarker{})
}
func (s *server) sendStreamingResults(sc *streamClient) {
ctx := sc.stream.Context()
peer, _ := peer.FromContext(ctx)
s.l.Printf("sending streaming results from target %q to peer %q", sc.target, peer.Addr)
defer s.subscribeRPCsem.Release(1)
for {
item, dup, err := sc.queue.Next(ctx)
if coalesce.IsClosedQueue(err) {
sc.errChan <- nil
return
}
if err != nil {
sc.errChan <- err
return
}
if _, ok := item.(syncMarker); ok {
err = sc.stream.Send(&gnmi.SubscribeResponse{
Response: &gnmi.SubscribeResponse_SyncResponse{
SyncResponse: true,
}})
if err != nil {
sc.errChan <- err
return
}
continue
}
node, ok := item.(*ctree.Leaf)
if !ok || node == nil {
sc.errChan <- status.Errorf(codes.Internal, "invalid cache node: %+v", item)
return
}
err = s.sendSubscribeResponse(&resp{
stream: sc.stream,
n: node,
dup: dup,
}, sc)
if err != nil {
s.l.Printf("target %q: failed sending subscribeResponse: %v", sc.target, err)
sc.errChan <- err
return
}
// TODO: check if target was deleted ? necessary ?
}
}
func (s *server) handlePolledSubscription(sc *streamClient) {
s.handleSubscriptionRequest(sc)
var err error
for {
if sc.queue.IsClosed() {
return
}
_, err = sc.stream.Recv()
if errors.Is(err, io.EOF) {
return
}
if err != nil {
s.l.Printf("target %q: failed poll subscription rcv: %v", sc.target, err)
sc.errChan <- err
return
}
s.l.Printf("target %q: repoll", sc.target)
s.handleSubscriptionRequest(sc)
s.l.Printf("target %q: repoll done", sc.target)
}
}
func (s *server) sendSubscribeResponse(r *resp, _ *streamClient) error {
notif, err := makeSubscribeResponse(r.n.Value(), r.dup)
if err != nil {
return status.Errorf(codes.Unknown, "unknown error: %v", err)
}
// No acls
return r.stream.Send(notif)
}
func makeSubscribeResponse(n interface{}, _ uint32) (*gnmi.SubscribeResponse, error) {
var notification *gnmi.Notification
var ok bool
notification, ok = n.(*gnmi.Notification)
if !ok {
return nil, status.Errorf(codes.Internal, "invalid notification type: %#v", n)
}
return &gnmi.SubscribeResponse{
Response: &gnmi.SubscribeResponse_Update{
Update: notification,
},
}, nil
}