34e17c1215be4c763689f5682b08c0863a0bd5a2
[govpp.git] / api / api.go
1 // Copyright (c) 2017 Cisco and/or its affiliates.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package api
16
17 import (
18         "errors"
19         "fmt"
20         "time"
21
22         "github.com/sirupsen/logrus"
23 )
24
25 // MessageType represents the type of a VPP message.
26 type MessageType int
27
28 const (
29         // RequestMessage represents a VPP request message
30         RequestMessage MessageType = iota
31         // ReplyMessage represents a VPP reply message
32         ReplyMessage
33         // EventMessage represents a VPP notification event message
34         EventMessage
35         // OtherMessage represents other VPP message (e.g. counters)
36         OtherMessage
37 )
38
39 // Message is an interface that is implemented by all VPP Binary API messages generated by the binapigenerator.
40 type Message interface {
41         // GetMessageName returns the original VPP name of the message, as defined in the VPP API.
42         GetMessageName() string
43
44         // GetMessageType returns the type of the VPP message.
45         GetMessageType() MessageType
46
47         // GetCrcString returns the string with CRC checksum of the message definition (the string represents a hexadecimal number).
48         GetCrcString() string
49 }
50
51 // DataType is an interface that is implemented by all VPP Binary API data types by the binapi_generator.
52 type DataType interface {
53         // GetTypeName returns the original VPP name of the data type, as defined in the VPP API.
54         GetTypeName() string
55
56         // GetCrcString returns the string with CRC checksum of the data type definition (the string represents a hexadecimal number).
57         GetCrcString() string
58 }
59
60 // ChannelProvider provides the communication channel with govpp core.
61 type ChannelProvider interface {
62         // NewAPIChannel returns a new channel for communication with VPP via govpp core.
63         // It uses default buffer sizes for the request and reply Go channels.
64         NewAPIChannel() (*Channel, error)
65
66         // NewAPIChannelBuffered returns a new channel for communication with VPP via govpp core.
67         // It allows to specify custom buffer sizes for the request and reply Go channels.
68         NewAPIChannelBuffered() (*Channel, error)
69 }
70
71 // MessageDecoder provides functionality for decoding binary data to generated API messages.
72 type MessageDecoder interface {
73         // DecodeMsg decodes binary-encoded data of a message into provided Message structure.
74         DecodeMsg(data []byte, msg Message) error
75 }
76
77 // MessageIdentifier provides identification of generated API messages.
78 type MessageIdentifier interface {
79         // GetMessageID returns message identifier of given API message.
80         GetMessageID(msg Message) (uint16, error)
81         // LookupByID looks up message name and crc by ID
82         LookupByID(ID uint16) (string, error)
83 }
84
85 // Channel is the main communication interface with govpp core. It contains two Go channels, one for sending the requests
86 // to VPP and one for receiving the replies from it. The user can access the Go channels directly, or use the helper
87 // methods  provided inside of this package. Do not use the same channel from multiple goroutines concurrently,
88 // otherwise the responses could mix! Use multiple channels instead.
89 type Channel struct {
90         ID uint16 // channel ID
91
92         ReqChan   chan *VppRequest // channel for sending the requests to VPP, closing this channel releases all resources in the ChannelProvider
93         ReplyChan chan *VppReply   // channel where VPP replies are delivered to
94
95         NotifSubsChan      chan *NotifSubscribeRequest // channel for sending notification subscribe requests
96         NotifSubsReplyChan chan error                  // channel where replies to notification subscribe requests are delivered to
97
98         MsgDecoder    MessageDecoder    // used to decode binary data to generated API messages
99         MsgIdentifier MessageIdentifier // used to retrieve message ID of a message
100
101         lastSeqNum uint16 // sequence number of the last sent request
102
103         delayedReply *VppReply     // reply already taken from ReplyChan, buffered for later delivery
104         replyTimeout time.Duration // maximum time that the API waits for a reply from VPP before returning an error, can be set with SetReplyTimeout
105 }
106
107 // VppRequest is a request that will be sent to VPP.
108 type VppRequest struct {
109         SeqNum    uint16  // sequence number
110         Message   Message // binary API message to be send to VPP
111         Multipart bool    // true if multipart response is expected, false otherwise
112 }
113
114 // VppReply is a reply received from VPP.
115 type VppReply struct {
116         MessageID         uint16 // ID of the message
117         SeqNum            uint16 // sequence number
118         Data              []byte // encoded data with the message - MessageDecoder can be used for decoding
119         LastReplyReceived bool   // in case of multipart replies, true if the last reply has been already received and this one should be ignored
120         Error             error  // in case of error, data is nil and this member contains error description
121 }
122
123 // NotifSubscribeRequest is a request to subscribe for delivery of specific notification messages.
124 type NotifSubscribeRequest struct {
125         Subscription *NotifSubscription // subscription details
126         Subscribe    bool               // true if this is a request to subscribe, false if unsubscribe
127 }
128
129 // NotifSubscription represents a subscription for delivery of specific notification messages.
130 type NotifSubscription struct {
131         NotifChan  chan Message   // channel where notification messages will be delivered to
132         MsgFactory func() Message // function that returns a new instance of the specific message that is expected as a notification
133 }
134
135 // RequestCtx is a context of a ongoing request (simple one - only one response is expected).
136 type RequestCtx struct {
137         ch     *Channel
138         seqNum uint16
139 }
140
141 // MultiRequestCtx is a context of a ongoing multipart request (multiple responses are expected).
142 type MultiRequestCtx struct {
143         ch     *Channel
144         seqNum uint16
145 }
146
147 const defaultReplyTimeout = time.Second * 1 // default timeout for replies from VPP, can be changed with SetReplyTimeout
148
149 // NewChannelInternal returns a new channel structure.
150 // Note that this is just a raw channel not yet connected to VPP, it is not intended to be used directly.
151 // Use ChannelProvider to get an API channel ready for communication with VPP.
152 func NewChannelInternal(id uint16) *Channel {
153         return &Channel{
154                 ID:           id,
155                 replyTimeout: defaultReplyTimeout,
156         }
157 }
158
159 // SetReplyTimeout sets the timeout for replies from VPP. It represents the maximum time the API waits for a reply
160 // from VPP before returning an error.
161 func (ch *Channel) SetReplyTimeout(timeout time.Duration) {
162         ch.replyTimeout = timeout
163 }
164
165 // Close closes the API channel and releases all API channel-related resources in the ChannelProvider.
166 func (ch *Channel) Close() {
167         if ch.ReqChan != nil {
168                 close(ch.ReqChan)
169         }
170 }
171
172 // SendRequest asynchronously sends a request to VPP. Returns a request context, that can be used to call ReceiveReply.
173 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
174 func (ch *Channel) SendRequest(msg Message) *RequestCtx {
175         ch.lastSeqNum++
176         ch.ReqChan <- &VppRequest{
177                 Message: msg,
178                 SeqNum:  ch.lastSeqNum,
179         }
180         return &RequestCtx{ch: ch, seqNum: ch.lastSeqNum}
181 }
182
183 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
184 // The reply will be decoded into the msg argument. Error will be returned if the response cannot be received or decoded.
185 func (req *RequestCtx) ReceiveReply(msg Message) error {
186         if req == nil || req.ch == nil {
187                 return errors.New("invalid request context")
188         }
189
190         lastReplyReceived, err := req.ch.receiveReplyInternal(msg, req.seqNum)
191
192         if lastReplyReceived {
193                 err = errors.New("multipart reply recieved while a simple reply expected")
194         }
195         return err
196 }
197
198 // SendMultiRequest asynchronously sends a multipart request (request to which multiple responses are expected) to VPP.
199 // Returns a multipart request context, that can be used to call ReceiveReply.
200 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
201 func (ch *Channel) SendMultiRequest(msg Message) *MultiRequestCtx {
202         ch.lastSeqNum++
203         ch.ReqChan <- &VppRequest{
204                 Message:   msg,
205                 Multipart: true,
206                 SeqNum:    ch.lastSeqNum,
207         }
208         return &MultiRequestCtx{ch: ch, seqNum: ch.lastSeqNum}
209 }
210
211 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
212 // The reply will be decoded into the msg argument. If the last reply has been already consumed, lastReplyReceived is
213 // set to true. Do not use the message itself if lastReplyReceived is true - it won't be filled with actual data.
214 // Error will be returned if the response cannot be received or decoded.
215 func (req *MultiRequestCtx) ReceiveReply(msg Message) (lastReplyReceived bool, err error) {
216         if req == nil || req.ch == nil {
217                 return false, errors.New("invalid request context")
218         }
219
220         return req.ch.receiveReplyInternal(msg, req.seqNum)
221 }
222
223 // receiveReplyInternal receives a reply from the reply channel into the provided msg structure.
224 func (ch *Channel) receiveReplyInternal(msg Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
225         var ignore bool
226         if msg == nil {
227                 return false, errors.New("nil message passed in")
228         }
229
230         if ch.delayedReply != nil {
231                 // try the delayed reply
232                 vppReply := ch.delayedReply
233                 ch.delayedReply = nil
234                 ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
235                 if !ignore {
236                         return lastReplyReceived, err
237                 }
238         }
239
240         timer := time.NewTimer(ch.replyTimeout)
241         for {
242                 select {
243                 // blocks until a reply comes to ReplyChan or until timeout expires
244                 case vppReply := <-ch.ReplyChan:
245                         ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
246                         if ignore {
247                                 continue
248                         }
249                         return lastReplyReceived, err
250
251                 case <-timer.C:
252                         err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
253                         return false, err
254                 }
255         }
256         return
257 }
258
259 func (ch *Channel) processReply(reply *VppReply, expSeqNum uint16, msg Message) (ignore bool, lastReplyReceived bool, err error) {
260         // check the sequence number
261         cmpSeqNums := compareSeqNumbers(reply.SeqNum, expSeqNum)
262         if cmpSeqNums == -1 {
263                 // reply received too late, ignore the message
264                 logrus.WithField("sequence-number", reply.SeqNum).Warn(
265                         "Received reply to an already closed binary API request")
266                 ignore = true
267                 return
268         }
269         if cmpSeqNums == 1 {
270                 ch.delayedReply = reply
271                 err = fmt.Errorf("missing binary API reply with sequence number: %d", expSeqNum)
272                 return
273         }
274
275         if reply.Error != nil {
276                 err = reply.Error
277                 return
278         }
279         if reply.LastReplyReceived {
280                 lastReplyReceived = true
281                 return
282         }
283
284         // message checks
285         var expMsgID uint16
286         expMsgID, err = ch.MsgIdentifier.GetMessageID(msg)
287         if err != nil {
288                 err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
289                         msg.GetMessageName(), msg.GetCrcString())
290                 return
291         }
292
293         if reply.MessageID != expMsgID {
294                 var msgNameCrc string
295                 if nameCrc, err := ch.MsgIdentifier.LookupByID(reply.MessageID); err != nil {
296                         msgNameCrc = err.Error()
297                 } else {
298                         msgNameCrc = nameCrc
299                 }
300
301                 err = fmt.Errorf("received invalid message ID (seq-num=%d), expected %d (%s), but got %d (%s) "+
302                         "(check if multiple goroutines are not sharing single GoVPP channel)",
303                         reply.SeqNum, expMsgID, msg.GetMessageName(), reply.MessageID, msgNameCrc)
304                 return
305         }
306
307         // decode the message
308         err = ch.MsgDecoder.DecodeMsg(reply.Data, msg)
309         return
310 }
311
312 // compareSeqNumbers returns -1, 0, 1 if sequence number <seqNum1> precedes, equals to,
313 // or succeeds seq. number <seqNum2>.
314 // Since sequence numbers cycle in the finite set of size 2^16, the function
315 // must assume that the distance between compared sequence numbers is less than
316 // (2^16)/2 to determine the order.
317 func compareSeqNumbers(seqNum1, seqNum2 uint16) int {
318         // calculate distance from seqNum1 to seqNum2
319         var dist uint16
320         if seqNum1 <= seqNum2 {
321                 dist = seqNum2 - seqNum1
322         } else {
323                 dist = 0xffff - (seqNum1 - seqNum2 - 1)
324         }
325         if dist == 0 {
326                 return 0
327         } else if dist <= 0x8000 {
328                 return -1
329         }
330         return 1
331 }
332
333 // SubscribeNotification subscribes for receiving of the specified notification messages via provided Go channel.
334 // Note that the caller is responsible for creating the Go channel with preferred buffer size. If the channel's
335 // buffer is full, the notifications will not be delivered into it.
336 func (ch *Channel) SubscribeNotification(notifChan chan Message, msgFactory func() Message) (*NotifSubscription, error) {
337         subscription := &NotifSubscription{
338                 NotifChan:  notifChan,
339                 MsgFactory: msgFactory,
340         }
341         ch.NotifSubsChan <- &NotifSubscribeRequest{
342                 Subscription: subscription,
343                 Subscribe:    true,
344         }
345         return subscription, <-ch.NotifSubsReplyChan
346 }
347
348 // UnsubscribeNotification unsubscribes from receiving the notifications tied to the provided notification subscription.
349 func (ch *Channel) UnsubscribeNotification(subscription *NotifSubscription) error {
350         ch.NotifSubsChan <- &NotifSubscribeRequest{
351                 Subscription: subscription,
352                 Subscribe:    false,
353         }
354         return <-ch.NotifSubsReplyChan
355 }
356
357 // CheckMessageCompatibility checks whether provided messages are compatible with the version of VPP
358 // which the library is connected to.
359 func (ch *Channel) CheckMessageCompatibility(messages ...Message) error {
360         for _, msg := range messages {
361                 _, err := ch.MsgIdentifier.GetMessageID(msg)
362                 if err != nil {
363                         return fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
364                                 msg.GetMessageName(), msg.GetCrcString())
365                 }
366         }
367         return nil
368 }