f478bf130b80936157db45a46927eac79c8b88e2
[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
23 // MessageType represents the type of a VPP message.
24 type MessageType int
25
26 const (
27         // RequestMessage represents a VPP request message
28         RequestMessage MessageType = iota
29         // ReplyMessage represents a VPP reply message
30         ReplyMessage
31         // OtherMessage represents other VPP message (e.g. counters)
32         OtherMessage
33 )
34
35 // Message is an interface that is implemented by all VPP Binary API messages generated by the binapi_generator.
36 type Message interface {
37         // GetMessageName returns the original VPP name of the message, as defined in the VPP API.
38         GetMessageName() string
39
40         // GetMessageType returns the type of the VPP message.
41         GetMessageType() MessageType
42
43         // GetCrcString returns the string with CRC checksum of the message definition (the string represents a hexadecimal number).
44         GetCrcString() string
45 }
46
47 // DataType is an interface that is implemented by all VPP Binary API data types by the binapi_generator.
48 type DataType interface {
49         // GetTypeName returns the original VPP name of the data type, as defined in the VPP API.
50         GetTypeName() string
51
52         // GetCrcString returns the string with CRC checksum of the data type definition (the string represents a hexadecimal number).
53         GetCrcString() string
54 }
55
56 // ChannelProvider provides the communication channel with govpp core.
57 type ChannelProvider interface {
58         // NewAPIChannel returns a new channel for communication with VPP via govpp core.
59         // It uses default buffer sizes for the request and reply Go channels.
60         NewAPIChannel() (*Channel, error)
61
62         // NewAPIChannel returns a new channel for communication with VPP via govpp core.
63         // It allows to specify custom buffer sizes for the request and reply Go channels.
64         NewAPIChannelBuffered() (*Channel, error)
65 }
66
67 // MessageDecoder provides functionality for decoding binary data to generated API messages.
68 type MessageDecoder interface {
69         // DecodeMsg decodes binary-encoded data of a message into provided Message structure.
70         DecodeMsg(data []byte, msg Message) error
71 }
72
73 // MessageIdentifier provides identification of generated API messages.
74 type MessageIdentifier interface {
75         // GetMessageID returns message identifier of given API message.
76         GetMessageID(msg Message) (uint16, error)
77 }
78
79 // Channel is the main communication interface with govpp core. It contains two Go channels, one for sending the requests
80 // to VPP and one for receiving the replies from it. The user can access the Go channels directly, or use the helper
81 // methods  provided inside of this package. Do not use the same channel from multiple goroutines concurrently,
82 // otherwise the responses could mix! Use multiple channels instead.
83 type Channel struct {
84         ReqChan   chan *VppRequest // channel for sending the requests to VPP, closing this channel releases all resources in the ChannelProvider
85         ReplyChan chan *VppReply   // channel where VPP replies are delivered to
86
87         NotifSubsChan      chan *NotifSubscribeRequest // channel for sending notification subscribe requests
88         NotifSubsReplyChan chan error                  // channel where replies to notification subscribe requests are delivered to
89
90         MsgDecoder    MessageDecoder    // used to decode binary data to generated API messages
91         MsgIdentifier MessageIdentifier // used to retrieve message ID of a message
92
93         replyTimeout time.Duration // maximum time that the API waits for a reply from VPP before returning an error, can be set with SetReplyTimeout
94         metadata     interface{}   // opaque metadata of the API channel
95 }
96
97 // VppRequest is a request that will be sent to VPP.
98 type VppRequest struct {
99         Message   Message // binary API message to be send to VPP
100         Multipart bool    // true if multipart response is expected, false otherwise
101 }
102
103 // VppReply is a reply received from VPP.
104 type VppReply struct {
105         MessageID         uint16 // ID of the message
106         Data              []byte // encoded data with the message - MessageDecoder can be used for decoding
107         LastReplyReceived bool   // in case of multipart replies, true if the last reply has been already received and this one should be ignored
108         Error             error  // in case of error, data is nil and this member contains error description
109 }
110
111 // NotifSubscribeRequest is a request to subscribe for delivery of specific notification messages.
112 type NotifSubscribeRequest struct {
113         Subscription *NotifSubscription // subscription details
114         Subscribe    bool               // true if this is a request to subscribe, false if unsubscribe
115 }
116
117 // NotifSubscription represents a subscription for delivery of specific notification messages.
118 type NotifSubscription struct {
119         NotifChan  chan Message   // channel where notification messages will be delivered to
120         MsgFactory func() Message // function that returns a new instance of the specific message that is expected as a notification
121 }
122
123 // RequestCtx is a context of a ongoing request (simple one - only one response is expected).
124 type RequestCtx struct {
125         ch *Channel
126 }
127
128 // MultiRequestCtx is a context of a ongoing multipart request (multiple responses are expected).
129 type MultiRequestCtx struct {
130         ch *Channel
131 }
132
133 const defaultReplyTimeout = time.Second * 1 // default timeout for replies from VPP, can be changed with SetReplyTimeout
134
135 // NewChannelInternal returns a new channel structure with metadata field filled in with the provided argument.
136 // Note that this is just a raw channel not yet connected to VPP, it is not intended to be used directly.
137 // Use ChannelProvider to get an API channel ready for communication with VPP.
138 func NewChannelInternal(metadata interface{}) *Channel {
139         return &Channel{
140                 replyTimeout: defaultReplyTimeout,
141                 metadata:     metadata,
142         }
143 }
144
145 // Metadata returns the metadata stored within the channel structure by the NewChannelInternal call.
146 func (ch *Channel) Metadata() interface{} {
147         return ch.metadata
148 }
149
150 // SetReplyTimeout sets the timeout for replies from VPP. It represents the maximum time the API waits for a reply
151 // from VPP before returning an error.
152 func (ch *Channel) SetReplyTimeout(timeout time.Duration) {
153         ch.replyTimeout = timeout
154 }
155
156 // Close closes the API channel and releases all API channel-related resources in the ChannelProvider.
157 func (ch *Channel) Close() {
158         if ch.ReqChan != nil {
159                 close(ch.ReqChan)
160         }
161 }
162
163 // SendRequest asynchronously sends a request to VPP. Returns a request context, that can be used to call ReceiveReply.
164 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
165 func (ch *Channel) SendRequest(msg Message) *RequestCtx {
166         ch.ReqChan <- &VppRequest{
167                 Message: msg,
168         }
169         return &RequestCtx{ch: ch}
170 }
171
172 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
173 // The reply will be decoded into the msg argument. Error will be returned if the response cannot be received or decoded.
174 func (req *RequestCtx) ReceiveReply(msg Message) error {
175         if req == nil || req.ch == nil {
176                 return errors.New("invalid request context")
177         }
178
179         lastReplyReceived, err := req.ch.receiveReplyInternal(msg)
180
181         if lastReplyReceived {
182                 err = errors.New("multipart reply recieved while a simple reply expected")
183         }
184         return err
185 }
186
187 // SendMultiRequest asynchronously sends a multipart request (request to which multiple responses are expected) to VPP.
188 // Returns a multipart request context, that can be used to call ReceiveReply.
189 // In case of any errors by sending, the error will be delivered to ReplyChan (and returned by ReceiveReply).
190 func (ch *Channel) SendMultiRequest(msg Message) *MultiRequestCtx {
191         ch.ReqChan <- &VppRequest{
192                 Message:   msg,
193                 Multipart: true,
194         }
195         return &MultiRequestCtx{ch: ch}
196 }
197
198 // ReceiveReply receives a reply from VPP (blocks until a reply is delivered from VPP, or until an error occurs).
199 // The reply will be decoded into the msg argument. If the last reply has been already consumed, LastReplyReceived is
200 // set to true. Do not use the message itself if LastReplyReceived is true - it won't be filled with actual data.
201 // Error will be returned if the response cannot be received or decoded.
202 func (req *MultiRequestCtx) ReceiveReply(msg Message) (LastReplyReceived bool, err error) {
203         if req == nil || req.ch == nil {
204                 return false, errors.New("invalid request context")
205         }
206
207         return req.ch.receiveReplyInternal(msg)
208 }
209
210 // receiveReplyInternal receives a reply from the reply channel into the provided msg structure.
211 func (ch *Channel) receiveReplyInternal(msg Message) (LastReplyReceived bool, err error) {
212         if msg == nil {
213                 return false, errors.New("nil message passed in")
214         }
215         select {
216         // blocks until a reply comes to ReplyChan or until timeout expires
217         case vppReply := <-ch.ReplyChan:
218                 if vppReply.Error != nil {
219                         err = vppReply.Error
220                         return
221                 }
222                 if vppReply.LastReplyReceived {
223                         LastReplyReceived = true
224                         return
225                 }
226                 // message checks
227                 expMsgID, err := ch.MsgIdentifier.GetMessageID(msg)
228                 if err != nil {
229                         err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
230                                 msg.GetMessageName(), msg.GetCrcString())
231                         return false, err
232                 }
233                 if vppReply.MessageID != expMsgID {
234                         err = fmt.Errorf("invalid message ID %d, expected %d "+
235                                 "(also check if multiple goroutines are not sharing one GoVPP channel)", vppReply.MessageID, expMsgID)
236                         return false, err
237                 }
238                 // decode the message
239                 err = ch.MsgDecoder.DecodeMsg(vppReply.Data, msg)
240
241         case <-time.After(ch.replyTimeout):
242                 err = fmt.Errorf("no reply received within the timeout period %ds", ch.replyTimeout/time.Second)
243         }
244         return
245 }
246
247 // SubscribeNotification subscribes for receiving of the specified notification messages via provided Go channel.
248 // Note that the caller is responsible for creating the Go channel with preferred buffer size. If the channel's
249 // buffer is full, the notifications will not be delivered into it.
250 func (ch *Channel) SubscribeNotification(notifChan chan Message, msgFactory func() Message) (*NotifSubscription, error) {
251         subscription := &NotifSubscription{
252                 NotifChan:  notifChan,
253                 MsgFactory: msgFactory,
254         }
255         ch.NotifSubsChan <- &NotifSubscribeRequest{
256                 Subscription: subscription,
257                 Subscribe:    true,
258         }
259         return subscription, <-ch.NotifSubsReplyChan
260 }
261
262 // UnsubscribeNotification unsubscribes from receiving the notifications tied to the provided notification subscription.
263 func (ch *Channel) UnsubscribeNotification(subscription *NotifSubscription) error {
264         ch.NotifSubsChan <- &NotifSubscribeRequest{
265                 Subscription: subscription,
266                 Subscribe:    false,
267         }
268         return <-ch.NotifSubsReplyChan
269 }
270
271 // CheckMessageCompatibility checks whether provided messages are compatible with the version of VPP
272 // which the library is connected to.
273 func (ch *Channel) CheckMessageCompatibility(messages ...Message) error {
274         for _, msg := range messages {
275                 _, err := ch.MsgIdentifier.GetMessageID(msg)
276                 if err != nil {
277                         return fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
278                                 msg.GetMessageName(), msg.GetCrcString())
279                 }
280         }
281         return nil
282 }