Lookup message name by ID when receiving unexpected message
[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         ReqChan   chan *VppRequest // channel for sending the requests to VPP, closing this channel releases all resources in the ChannelProvider
91         ReplyChan chan *VppReply   // channel where VPP replies are delivered to
92
93         NotifSubsChan      chan *NotifSubscribeRequest // channel for sending notification subscribe requests
94         NotifSubsReplyChan chan error                  // channel where replies to notification subscribe requests are delivered to
95
96         MsgDecoder    MessageDecoder    // used to decode binary data to generated API messages
97         MsgIdentifier MessageIdentifier // used to retrieve message ID of a message
98
99         replyTimeout time.Duration // maximum time that the API waits for a reply from VPP before returning an error, can be set with SetReplyTimeout
100         metadata     interface{}   // opaque metadata of the API channel
101         lastTimedOut bool          // wether last request timed out
102 }
103
104 // VppRequest is a request that will be sent to VPP.
105 type VppRequest struct {
106         Message   Message // binary API message to be send to VPP
107         Multipart bool    // true if multipart response is expected, false otherwise
108 }
109
110 // VppReply is a reply received from VPP.
111 type VppReply struct {
112         MessageID         uint16 // ID of the message
113         Data              []byte // encoded data with the message - MessageDecoder can be used for decoding
114         LastReplyReceived bool   // in case of multipart replies, true if the last reply has been already received and this one should be ignored
115         Error             error  // in case of error, data is nil and this member contains error description
116 }
117
118 // NotifSubscribeRequest is a request to subscribe for delivery of specific notification messages.
119 type NotifSubscribeRequest struct {
120         Subscription *NotifSubscription // subscription details
121         Subscribe    bool               // true if this is a request to subscribe, false if unsubscribe
122 }
123
124 // NotifSubscription represents a subscription for delivery of specific notification messages.
125 type NotifSubscription struct {
126         NotifChan  chan Message   // channel where notification messages will be delivered to
127         MsgFactory func() Message // function that returns a new instance of the specific message that is expected as a notification
128 }
129
130 // RequestCtx is a context of a ongoing request (simple one - only one response is expected).
131 type RequestCtx struct {
132         ch *Channel
133 }
134
135 // MultiRequestCtx is a context of a ongoing multipart request (multiple responses are expected).
136 type MultiRequestCtx struct {
137         ch *Channel
138 }
139
140 const defaultReplyTimeout = time.Second * 1 // default timeout for replies from VPP, can be changed with SetReplyTimeout
141
142 // NewChannelInternal returns a new channel structure with metadata field filled in with the provided argument.
143 // Note that this is just a raw channel not yet connected to VPP, it is not intended to be used directly.
144 // Use ChannelProvider to get an API channel ready for communication with VPP.
145 func NewChannelInternal(metadata interface{}) *Channel {
146         return &Channel{
147                 replyTimeout: defaultReplyTimeout,
148                 metadata:     metadata,
149         }
150 }
151
152 // Metadata returns the metadata stored within the channel structure by the NewChannelInternal call.
153 func (ch *Channel) Metadata() interface{} {
154         return ch.metadata
155 }
156
157 // SetReplyTimeout sets the timeout for replies from VPP. It represents the maximum time the API waits for a reply
158 // from VPP before returning an error.
159 func (ch *Channel) SetReplyTimeout(timeout time.Duration) {
160         ch.replyTimeout = timeout
161 }
162
163 // Close closes the API channel and releases all API channel-related resources in the ChannelProvider.
164 func (ch *Channel) Close() {
165         if ch.ReqChan != nil {
166                 close(ch.ReqChan)
167         }
168 }
169
170 // SendRequest asynchronously sends a request to VPP. Returns a request context, that can be used to call ReceiveReply.
171 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
172 func (ch *Channel) SendRequest(msg Message) *RequestCtx {
173         ch.ReqChan <- &VppRequest{
174                 Message: msg,
175         }
176         return &RequestCtx{ch: ch}
177 }
178
179 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
180 // The reply will be decoded into the msg argument. Error will be returned if the response cannot be received or decoded.
181 func (req *RequestCtx) ReceiveReply(msg Message) error {
182         if req == nil || req.ch == nil {
183                 return errors.New("invalid request context")
184         }
185
186         lastReplyReceived, err := req.ch.receiveReplyInternal(msg)
187
188         if lastReplyReceived {
189                 err = errors.New("multipart reply recieved while a simple reply expected")
190         }
191         return err
192 }
193
194 // SendMultiRequest asynchronously sends a multipart request (request to which multiple responses are expected) to VPP.
195 // Returns a multipart request context, that can be used to call ReceiveReply.
196 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
197 func (ch *Channel) SendMultiRequest(msg Message) *MultiRequestCtx {
198         ch.ReqChan <- &VppRequest{
199                 Message:   msg,
200                 Multipart: true,
201         }
202         return &MultiRequestCtx{ch: ch}
203 }
204
205 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
206 // The reply will be decoded into the msg argument. If the last reply has been already consumed, LastReplyReceived is
207 // set to true. Do not use the message itself if LastReplyReceived is true - it won't be filled with actual data.
208 // Error will be returned if the response cannot be received or decoded.
209 func (req *MultiRequestCtx) ReceiveReply(msg Message) (LastReplyReceived bool, err error) {
210         if req == nil || req.ch == nil {
211                 return false, errors.New("invalid request context")
212         }
213
214         return req.ch.receiveReplyInternal(msg)
215 }
216
217 // receiveReplyInternal receives a reply from the reply channel into the provided msg structure.
218 func (ch *Channel) receiveReplyInternal(msg Message) (LastReplyReceived bool, err error) {
219         if msg == nil {
220                 return false, errors.New("nil message passed in")
221         }
222
223         timer := time.NewTimer(ch.replyTimeout)
224         for {
225                 select {
226                 // blocks until a reply comes to ReplyChan or until timeout expires
227                 case vppReply := <-ch.ReplyChan:
228                         if vppReply.Error != nil {
229                                 err = vppReply.Error
230                                 return
231                         }
232                         if vppReply.LastReplyReceived {
233                                 LastReplyReceived = true
234                                 return
235                         }
236
237                         // message checks
238                         expMsgID, err := ch.MsgIdentifier.GetMessageID(msg)
239                         if err != nil {
240                                 err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
241                                         msg.GetMessageName(), msg.GetCrcString())
242                                 return false, err
243                         }
244
245                         if vppReply.MessageID != expMsgID {
246                                 var msgNameCrc string
247                                 if nameCrc, err := ch.MsgIdentifier.LookupByID(vppReply.MessageID); err != nil {
248                                         msgNameCrc = err.Error()
249                                 } else {
250                                         msgNameCrc = nameCrc
251                                 }
252
253                                 if ch.lastTimedOut {
254                                         logrus.Warnf("received invalid message ID, expected %d (%s), but got %d (%s) (probably timed out reply from previous request)",
255                                                 expMsgID, msg.GetMessageName(), vppReply.MessageID, msgNameCrc)
256                                         continue
257                                 }
258
259                                 err = fmt.Errorf("received invalid message ID, expected %d (%s), but got %d (%s) (check if multiple goroutines are not sharing single GoVPP channel)",
260                                         expMsgID, msg.GetMessageName(), vppReply.MessageID, msgNameCrc)
261                                 return false, err
262                         }
263
264                         ch.lastTimedOut = false
265                         // decode the message
266                         err = ch.MsgDecoder.DecodeMsg(vppReply.Data, msg)
267                         return false, err
268
269                 case <-timer.C:
270                         ch.lastTimedOut = true
271                         err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
272                         return false, err
273                 }
274         }
275         return
276 }
277
278 // SubscribeNotification subscribes for receiving of the specified notification messages via provided Go channel.
279 // Note that the caller is responsible for creating the Go channel with preferred buffer size. If the channel's
280 // buffer is full, the notifications will not be delivered into it.
281 func (ch *Channel) SubscribeNotification(notifChan chan Message, msgFactory func() Message) (*NotifSubscription, error) {
282         subscription := &NotifSubscription{
283                 NotifChan:  notifChan,
284                 MsgFactory: msgFactory,
285         }
286         ch.NotifSubsChan <- &NotifSubscribeRequest{
287                 Subscription: subscription,
288                 Subscribe:    true,
289         }
290         return subscription, <-ch.NotifSubsReplyChan
291 }
292
293 // UnsubscribeNotification unsubscribes from receiving the notifications tied to the provided notification subscription.
294 func (ch *Channel) UnsubscribeNotification(subscription *NotifSubscription) error {
295         ch.NotifSubsChan <- &NotifSubscribeRequest{
296                 Subscription: subscription,
297                 Subscribe:    false,
298         }
299         return <-ch.NotifSubsReplyChan
300 }
301
302 // CheckMessageCompatibility checks whether provided messages are compatible with the version of VPP
303 // which the library is connected to.
304 func (ch *Channel) CheckMessageCompatibility(messages ...Message) error {
305         for _, msg := range messages {
306                 _, err := ch.MsgIdentifier.GetMessageID(msg)
307                 if err != nil {
308                         return fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
309                                 msg.GetMessageName(), msg.GetCrcString())
310                 }
311         }
312         return nil
313 }