1 // Copyright (c) 2018 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.
24 "github.com/sirupsen/logrus"
26 "git.fd.io/govpp.git/adapter"
27 "git.fd.io/govpp.git/api"
31 ErrInvalidRequestCtx = errors.New("invalid request context")
34 // MessageCodec provides functionality for decoding binary data to generated API messages.
35 type MessageCodec interface {
36 // EncodeMsg encodes message into binary data.
37 EncodeMsg(msg api.Message, msgID uint16) ([]byte, error)
38 // DecodeMsg decodes binary-encoded data of a message into provided Message structure.
39 DecodeMsg(data []byte, msg api.Message) error
42 // MessageIdentifier provides identification of generated API messages.
43 type MessageIdentifier interface {
44 // GetMessageID returns message identifier of given API message.
45 GetMessageID(msg api.Message) (uint16, error)
46 // LookupByID looks up message name and crc by ID
47 LookupByID(msgID uint16) (api.Message, error)
50 // vppRequest is a request that will be sent to VPP.
51 type vppRequest struct {
52 seqNum uint16 // sequence number
53 msg api.Message // binary API message to be send to VPP
54 multi bool // true if multipart response is expected
57 // vppReply is a reply received from VPP.
58 type vppReply struct {
59 seqNum uint16 // sequence number
60 msgID uint16 // ID of the message
61 data []byte // encoded data with the message
62 lastReceived bool // for multi request, true if the last reply has been already received
63 err error // in case of error, data is nil and this member contains error
66 // requestCtx is a context for request with single reply
67 type requestCtx struct {
72 // multiRequestCtx is a context for request with multiple responses
73 type multiRequestCtx struct {
78 // subscriptionCtx is a context of subscription for delivery of specific notification messages.
79 type subscriptionCtx struct {
81 notifChan chan api.Message // channel where notification messages will be delivered to
82 msgID uint16 // message ID for the subscribed event message
83 event api.Message // event message that this subscription is for
84 msgFactory func() api.Message // function that returns a new instance of the specific message that is expected as a notification
87 // channel is the main communication interface with govpp core. It contains four Go channels, one for sending the requests
88 // to VPP, one for receiving the replies from it and the same set for notifications. The user can access the Go channels
89 // via methods provided by Channel interface in this package. Do not use the same channel from multiple goroutines
90 // concurrently, otherwise the responses could mix! Use multiple channels instead.
95 reqChan chan *vppRequest // channel for sending the requests to VPP
96 replyChan chan *vppReply // channel where VPP replies are delivered to
98 msgCodec MessageCodec // used to decode binary data to generated API messages
99 msgIdentifier MessageIdentifier // used to retrieve message ID of a message
101 lastSeqNum uint16 // sequence number of the last sent request
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
107 func newChannel(id uint16, conn *Connection, codec MessageCodec, identifier MessageIdentifier, reqSize, replySize int) *Channel {
112 msgIdentifier: identifier,
113 reqChan: make(chan *vppRequest, reqSize),
114 replyChan: make(chan *vppReply, replySize),
115 replyTimeout: DefaultReplyTimeout,
119 func (ch *Channel) GetID() uint16 {
123 func (ch *Channel) nextSeqNum() uint16 {
128 func (ch *Channel) SendRequest(msg api.Message) api.RequestCtx {
129 seqNum := ch.nextSeqNum()
130 ch.reqChan <- &vppRequest{
134 return &requestCtx{ch: ch, seqNum: seqNum}
137 func (ch *Channel) SendMultiRequest(msg api.Message) api.MultiRequestCtx {
138 seqNum := ch.nextSeqNum()
139 ch.reqChan <- &vppRequest{
144 return &multiRequestCtx{ch: ch, seqNum: seqNum}
147 func (ch *Channel) CheckCompatiblity(msgs ...api.Message) error {
148 var comperr api.CompatibilityError
149 for _, msg := range msgs {
150 _, err := ch.msgIdentifier.GetMessageID(msg)
152 if uerr, ok := err.(*adapter.UnknownMsgError); ok {
153 m := fmt.Sprintf("%s_%s", uerr.MsgName, uerr.MsgCrc)
154 comperr.IncompatibleMessages = append(comperr.IncompatibleMessages, m)
157 // other errors return immediatelly
161 if len(comperr.IncompatibleMessages) == 0 {
167 func (ch *Channel) SubscribeNotification(notifChan chan api.Message, event api.Message) (api.SubscriptionCtx, error) {
168 msgID, err := ch.msgIdentifier.GetMessageID(event)
170 log.WithFields(logrus.Fields{
171 "msg_name": event.GetMessageName(),
172 "msg_crc": event.GetCrcString(),
173 }).Errorf("unable to retrieve message ID: %v", err)
174 return nil, fmt.Errorf("unable to retrieve event message ID: %v", err)
177 sub := &subscriptionCtx{
179 notifChan: notifChan,
182 msgFactory: getMsgFactory(event),
185 // add the subscription into map
186 ch.conn.subscriptionsLock.Lock()
187 defer ch.conn.subscriptionsLock.Unlock()
189 ch.conn.subscriptions[msgID] = append(ch.conn.subscriptions[msgID], sub)
194 func (ch *Channel) SetReplyTimeout(timeout time.Duration) {
195 ch.replyTimeout = timeout
198 func (ch *Channel) Close() {
202 func (req *requestCtx) ReceiveReply(msg api.Message) error {
203 if req == nil || req.ch == nil {
204 return ErrInvalidRequestCtx
207 lastReplyReceived, err := req.ch.receiveReplyInternal(msg, req.seqNum)
210 } else if lastReplyReceived {
211 return errors.New("multipart reply recieved while a single reply expected")
217 func (req *multiRequestCtx) ReceiveReply(msg api.Message) (lastReplyReceived bool, err error) {
218 if req == nil || req.ch == nil {
219 return false, ErrInvalidRequestCtx
222 return req.ch.receiveReplyInternal(msg, req.seqNum)
225 func (sub *subscriptionCtx) Unsubscribe() error {
226 log.WithFields(logrus.Fields{
227 "msg_name": sub.event.GetMessageName(),
229 }).Debug("Removing notification subscription.")
231 // remove the subscription from the map
232 sub.ch.conn.subscriptionsLock.Lock()
233 defer sub.ch.conn.subscriptionsLock.Unlock()
235 for i, item := range sub.ch.conn.subscriptions[sub.msgID] {
237 // remove i-th item in the slice
238 sub.ch.conn.subscriptions[sub.msgID] = append(sub.ch.conn.subscriptions[sub.msgID][:i], sub.ch.conn.subscriptions[sub.msgID][i+1:]...)
243 return fmt.Errorf("subscription for %q not found", sub.event.GetMessageName())
246 // receiveReplyInternal receives a reply from the reply channel into the provided msg structure.
247 func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
249 return false, errors.New("nil message passed in")
254 if vppReply := ch.delayedReply; vppReply != nil {
255 // try the delayed reply
256 ch.delayedReply = nil
257 ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
259 return lastReplyReceived, err
263 timer := time.NewTimer(ch.replyTimeout)
266 // blocks until a reply comes to ReplyChan or until timeout expires
267 case vppReply := <-ch.replyChan:
268 ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
270 log.WithFields(logrus.Fields{
271 "expSeqNum": expSeqNum,
273 }).Warnf("ignoring received reply: %+v (expecting: %s)", vppReply, msg.GetMessageName())
276 return lastReplyReceived, err
279 log.WithFields(logrus.Fields{
280 "expSeqNum": expSeqNum,
282 }).Debugf("timeout (%v) waiting for reply: %s", ch.replyTimeout, msg.GetMessageName())
283 err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
289 func (ch *Channel) processReply(reply *vppReply, expSeqNum uint16, msg api.Message) (ignore bool, lastReplyReceived bool, err error) {
290 // check the sequence number
291 cmpSeqNums := compareSeqNumbers(reply.seqNum, expSeqNum)
292 if cmpSeqNums == -1 {
293 // reply received too late, ignore the message
294 log.WithField("seqNum", reply.seqNum).
295 Warn("Received reply to an already closed binary API request")
300 ch.delayedReply = reply
301 err = fmt.Errorf("missing binary API reply with sequence number: %d", expSeqNum)
305 if reply.err != nil {
309 if reply.lastReceived {
310 lastReplyReceived = true
316 expMsgID, err = ch.msgIdentifier.GetMessageID(msg)
318 err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
319 msg.GetMessageName(), msg.GetCrcString())
323 if reply.msgID != expMsgID {
324 var msgNameCrc string
325 if replyMsg, err := ch.msgIdentifier.LookupByID(reply.msgID); err != nil {
326 msgNameCrc = err.Error()
328 msgNameCrc = getMsgNameWithCrc(replyMsg)
331 err = fmt.Errorf("received invalid message ID (seqNum=%d), expected %d (%s), but got %d (%s) "+
332 "(check if multiple goroutines are not sharing single GoVPP channel)",
333 reply.seqNum, expMsgID, msg.GetMessageName(), reply.msgID, msgNameCrc)
337 // decode the message
338 if err = ch.msgCodec.DecodeMsg(reply.data, msg); err != nil {
342 // check Retval and convert it into VnetAPIError error
343 if strings.HasSuffix(msg.GetMessageName(), "_reply") {
344 // TODO: use categories for messages to avoid checking message name
345 if f := reflect.Indirect(reflect.ValueOf(msg)).FieldByName("Retval"); f.IsValid() {
346 retval := int32(f.Int())
347 err = api.RetvalToVPPApiError(retval)