/
message.go
368 lines (301 loc) · 9.09 KB
/
message.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
package client
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/damianoneill/net/v2/netconf/common"
"github.com/damianoneill/net/v2/netconf/common/codec"
)
// The Message layer defines a set of base protocol operations
// invoked as RPC methods with XML-encoded parameters.
// Session represents a Netconf Session
type Session interface {
// Execute executes an RPC request on the server and returns the reply.
Execute(req common.Request) (*common.RPCReply, error)
// ExecuteAsync submits an RPC request for execution on the server, arranging for the
// reply to be sent to the supplied channel.
ExecuteAsync(req common.Request, rchan chan *common.RPCReply) (err error)
// Subscribe issues an RPC request and returns the reply. If successful, notifications will
// be sent to the supplied channel.
Subscribe(req common.Request, nchan chan *common.Notification) (reply *common.RPCReply, err error)
// Close closes the session and releases any associated resources.
// The channel will be automatically closed if the underlying network connection is closed, for
// example if the remote server discoonects.
// When the session is closed, any outstanding execute requests and reads from a notification
// channel will return nil.
Close()
// ID delivers the server-allocated id of the session.
ID() uint64
// Capabilities delivers the server-supplied capabilities.
ServerCapabilities() []string
}
type sesImpl struct {
cfg *Config
t Transport
dec *codec.Decoder
enc *codec.Encoder
trace *ClientTrace
pool []chan *common.RPCReply
hellochan chan bool
responseq []chan *common.RPCReply
subchan chan *common.Notification
hello *common.HelloMessage
reqLock sync.Mutex
pchLock sync.Mutex
rchLock sync.Mutex
notificationDropCount uint64
target string
}
// NewSession creates a new Netconf session, using the supplied Transport.
func NewSession(ctx context.Context, t Transport, cfg *Config) (Session, error) {
si := &sesImpl{
cfg: cfg,
t: t,
target: t.(*tImpl).target,
dec: codec.NewDecoder(t),
enc: codec.NewEncoder(t),
trace: ContextClientTrace(ctx),
hellochan: make(chan bool),
}
// Send hello
err := si.enc.Encode(&common.HelloMessage{Capabilities: si.clientCapabilities()})
if err != nil {
si.trace.Error("Failed to encode hello", si.target, err)
si.Close()
return nil, err
}
// Launch goroutine to handle incoming messages from the server.
go si.handleIncomingMessages()
err = si.waitForServerHello()
if err != nil {
si.trace.Error("Failed to receive hello", si.target, err)
si.Close()
return nil, err
}
return si, nil
}
func (si *sesImpl) clientCapabilities() []string {
if si.cfg.DisableChunkedCodec {
return common.NoChunkedCodecCapabilities
}
return common.DefaultCapabilities
}
func (si *sesImpl) Execute(req common.Request) (reply *common.RPCReply, err error) {
si.trace.ExecuteStart(req, false)
defer func(begin time.Time) {
si.trace.ExecuteDone(req, false, reply, err, time.Since(begin))
}(time.Now())
// Allocate a response channel
rchan := si.allocChan()
defer si.relChan(rchan)
// Submit the request
err = si.execute(req, rchan)
if err != nil {
return nil, err
}
// Wait for the response.
reply = <-rchan
err = mapError(reply)
return reply, err
}
func (si *sesImpl) ExecuteAsync(req common.Request, rchan chan *common.RPCReply) (err error) {
si.trace.ExecuteStart(req, true)
defer func(begin time.Time) {
si.trace.ExecuteDone(req, true, nil, err, time.Since(begin))
}(time.Now())
return si.execute(req, rchan)
}
func (si *sesImpl) execute(req common.Request, rchan chan *common.RPCReply) (err error) {
// Build the request to be submitted.
msg := &common.RPCMessage{MessageID: uuid.New().String(), Union: common.GetUnion(req)}
// Lock the request channel, so the request and response channel set up is atomic.
si.reqLock.Lock()
defer si.reqLock.Unlock()
// Add the response channel to the response queue, but take it off if the request was not
// submitted successfully.
si.pushRespChan(rchan)
if err = si.enc.Encode(msg); err != nil {
si.popRespChan()
}
return
}
func (si *sesImpl) Subscribe(req common.Request, nchan chan *common.Notification) (reply *common.RPCReply, err error) {
// Store the notification channel for the session.
si.subchan = nchan
return si.Execute(req)
}
func (si *sesImpl) Close() {
err := si.t.Close()
if err != nil {
si.trace.Error("Session close failed", si.target, err)
}
}
func (si *sesImpl) ID() uint64 {
return si.hello.SessionID
}
func (si *sesImpl) ServerCapabilities() []string {
return si.hello.Capabilities
}
func (si *sesImpl) waitForServerHello() (err error) {
select {
case result := <-si.hellochan:
if !result {
return errors.New("failed to get hello - remote closed connection?")
}
case <-time.After(time.Duration(si.cfg.SetupTimeoutSecs) * time.Second):
err = errors.New("failed to get hello from server")
}
return
}
func (si *sesImpl) handleIncomingMessages() {
// When this goroutine finishes, make sure anytbody waiting for an async response or notification
// gets informed.
defer si.closeChannels()
// Loop, looking for a start element type of hello, rpc-reply or notification.
for {
token, err := si.dec.Token()
if err != nil {
break
}
if err = si.handleToken(token); err != nil {
return
}
}
}
func (si *sesImpl) handleToken(token xml.Token) (err error) {
switch token := token.(type) {
case xml.StartElement:
switch token.Name.Local {
case common.NameHello.Local: // <hello>
err = si.handleHello(token)
case common.NameRPCReply.Local: // <rpc-reply>
err = si.handleRPCReply(token)
case common.NameNotification.Local: // <notification>
err = si.handleNotification(token)
default:
}
default:
}
return
}
func (si *sesImpl) handleHello(token xml.StartElement) (err error) {
// Decode the hello element and send it down the channel to trigger the rest of the session setup.
if err = si.decodeElement(&si.hello, &token); err != nil {
si.hellochan <- false
return
}
if !si.cfg.DisableChunkedCodec && common.PeerSupportsChunkedFraming(si.hello.Capabilities) {
// Update the codec to use chunked framing from now.
codec.EnableChunkedFraming(si.dec, si.enc)
}
si.hellochan <- true
si.trace.HelloDone(si.hello)
return
}
func (si *sesImpl) handleRPCReply(token xml.StartElement) (err error) {
reply := common.RPCReply{}
if err = si.decodeElement(&reply, &token); err != nil {
return
}
// Pop the channel off the head of the queue and send the reply to it.
respch := si.popRespChan()
go func(ch chan *common.RPCReply, r *common.RPCReply) {
ch <- r
}(respch, &reply)
return
}
func (si *sesImpl) handleNotification(token xml.StartElement) (err error) {
result := &common.NotificationMessage{}
if err = si.decodeElement(&result, &token); err != nil {
return
}
// Send notification to subscription channel, if it's defined and not full.
if si.subchan != nil {
notification := buildNotification(result)
si.trace.NotificationReceived(notification)
select {
case si.subchan <- notification:
default:
atomic.AddUint64(&si.notificationDropCount, 1)
si.trace.NotificationDropped(notification)
}
}
return
}
func buildNotification(nmsg *common.NotificationMessage) *common.Notification {
event := fmt.Sprintf(`<%s xmlns=%q>%s</%s>`,
nmsg.Event.XMLName.Local, nmsg.Event.XMLName.Space, nmsg.Event.Event, nmsg.Event.XMLName.Local)
notification := &common.Notification{XMLName: nmsg.Event.XMLName, EventTime: nmsg.EventTime, Event: event}
return notification
}
func (si *sesImpl) decodeElement(v interface{}, start *xml.StartElement) (err error) {
if err = si.dec.DecodeElement(v, start); err != nil {
si.trace.Error(fmt.Sprintf("DecodeElement token:%s", start.Name.Local), si.target, err)
}
return
}
func (si *sesImpl) closeChannels() {
close(si.hellochan)
if si.subchan != nil {
close(si.subchan)
}
si.closeAllResponseChannels()
}
func (si *sesImpl) closeAllResponseChannels() {
for {
if ch := si.popRespChan(); ch != nil {
close(ch)
} else {
return
}
}
}
func (si *sesImpl) allocChan() (ch chan *common.RPCReply) {
si.pchLock.Lock()
defer si.pchLock.Unlock()
l := len(si.pool)
if l == 0 {
return make(chan *common.RPCReply)
}
si.pool, ch = si.pool[:l-1], si.pool[l-1]
return
}
func (si *sesImpl) relChan(ch chan *common.RPCReply) {
si.pchLock.Lock()
defer si.pchLock.Unlock()
si.pool = append(si.pool, ch)
}
func (si *sesImpl) pushRespChan(ch chan *common.RPCReply) {
si.rchLock.Lock()
defer si.rchLock.Unlock()
si.responseq = append(si.responseq, ch)
}
func (si *sesImpl) popRespChan() (ch chan *common.RPCReply) {
si.rchLock.Lock()
defer si.rchLock.Unlock()
if len(si.responseq) > 0 {
si.responseq, ch = si.responseq[1:], si.responseq[0]
}
return
}
// Map an RPC reply to an error, if the reply is either null or contains any RPC error.
func mapError(r *common.RPCReply) (err error) {
if r == nil {
err = io.ErrUnexpectedEOF
} else if r.Errors != nil {
for i := 0; i < len(r.Errors); i++ {
rpcErr := r.Errors[i]
if rpcErr.Severity == "error" {
err = &rpcErr
break
}
}
}
return
}