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