1 // Copyright (c) 2017 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
23 // MessageType represents the type of a VPP message.
27 // RequestMessage represents a VPP request message
28 RequestMessage MessageType = iota
29 // ReplyMessage represents a VPP reply message
31 // EventMessage represents a VPP notification event message
33 // OtherMessage represents other VPP message (e.g. counters)
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
42 // GetMessageType returns the type of the VPP message.
43 GetMessageType() MessageType
45 // GetCrcString returns the string with CRC checksum of the message definition (the string represents a hexadecimal number).
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.
54 // GetCrcString returns the string with CRC checksum of the data type definition (the string represents a hexadecimal number).
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)
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)
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
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)
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.
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
89 NotifSubsChan chan *NotifSubscribeRequest // channel for sending notification subscribe requests
90 NotifSubsReplyChan chan error // channel where replies to notification subscribe requests are delivered to
92 MsgDecoder MessageDecoder // used to decode binary data to generated API messages
93 MsgIdentifier MessageIdentifier // used to retrieve message ID of a message
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
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
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
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
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
125 // RequestCtx is a context of a ongoing request (simple one - only one response is expected).
126 type RequestCtx struct {
130 // MultiRequestCtx is a context of a ongoing multipart request (multiple responses are expected).
131 type MultiRequestCtx struct {
135 const defaultReplyTimeout = time.Second * 1 // default timeout for replies from VPP, can be changed with SetReplyTimeout
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 {
142 replyTimeout: defaultReplyTimeout,
147 // Metadata returns the metadata stored within the channel structure by the NewChannelInternal call.
148 func (ch *Channel) Metadata() interface{} {
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
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 {
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{
171 return &RequestCtx{ch: ch}
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")
181 lastReplyReceived, err := req.ch.receiveReplyInternal(msg)
183 if lastReplyReceived {
184 err = errors.New("multipart reply recieved while a simple reply expected")
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{
197 return &MultiRequestCtx{ch: ch}
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")
209 return req.ch.receiveReplyInternal(msg)
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) {
215 return false, errors.New("nil message passed in")
218 // blocks until a reply comes to ReplyChan or until timeout expires
219 case vppReply := <-ch.ReplyChan:
220 if vppReply.Error != nil {
224 if vppReply.LastReplyReceived {
225 LastReplyReceived = true
229 expMsgID, err := ch.MsgIdentifier.GetMessageID(msg)
231 err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
232 msg.GetMessageName(), msg.GetCrcString())
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)
240 // decode the message
241 err = ch.MsgDecoder.DecodeMsg(vppReply.Data, msg)
243 case <-time.After(ch.replyTimeout):
244 err = fmt.Errorf("no reply received within the timeout period %ds", ch.replyTimeout/time.Second)
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,
257 ch.NotifSubsChan <- &NotifSubscribeRequest{
258 Subscription: subscription,
261 return subscription, <-ch.NotifSubsReplyChan
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,
270 return <-ch.NotifSubsReplyChan
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)
279 return fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
280 msg.GetMessageName(), msg.GetCrcString())