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 logger "github.com/sirupsen/logrus"
27 ErrNotConnected = errors.New("not connected to VPP, ignoring the request")
28 ErrProbeTimeout = errors.New("probe reply not received within timeout period")
31 // watchRequests watches for requests on the request API channel and forwards them as messages to VPP.
32 func (c *Connection) watchRequests(ch *Channel) {
35 case req, ok := <-ch.reqChan:
36 // new request on the request channel
38 // after closing the request channel, release API channel and return
39 c.releaseAPIChannel(ch)
42 c.processRequest(ch, req)
47 // processRequest processes a single request received on the request channel.
48 func (c *Connection) processRequest(ch *Channel, req *vppRequest) error {
49 // check whether we are connected to VPP
50 if atomic.LoadUint32(&c.connected) == 0 {
51 err := ErrNotConnected
52 log.Errorf("processing request failed: %v", err)
53 sendReplyError(ch, req, err)
57 // retrieve message ID
58 msgID, err := c.GetMessageID(req.msg)
60 err = fmt.Errorf("unable to retrieve message ID: %v", err)
61 log.WithFields(logger.Fields{
62 "msg_name": req.msg.GetMessageName(),
63 "msg_crc": req.msg.GetCrcString(),
64 "seq_num": req.seqNum,
66 sendReplyError(ch, req, err)
70 // encode the message into binary
71 data, err := c.codec.EncodeMsg(req.msg, msgID)
73 err = fmt.Errorf("unable to encode the messge: %v", err)
74 log.WithFields(logger.Fields{
77 "msg_name": req.msg.GetMessageName(),
78 "seq_num": req.seqNum,
80 sendReplyError(ch, req, err)
85 context := packRequestContext(ch.id, req.multi, req.seqNum)
86 if log.Level == logger.DebugLevel { // for performance reasons - logrus does some processing even if debugs are disabled
87 log.WithFields(logger.Fields{
90 "is_multi": req.multi,
92 "msg_name": req.msg.GetMessageName(),
93 "msg_size": len(data),
94 "seq_num": req.seqNum,
95 }).Debug(" -> Sending a message to VPP.")
98 // send the request to VPP
99 err = c.vpp.SendMsg(context, data)
101 err = fmt.Errorf("unable to send the message: %v", err)
102 log.WithFields(logger.Fields{
105 "seq_num": req.seqNum,
107 sendReplyError(ch, req, err)
112 // send a control ping to determine end of the multipart response
113 pingData, _ := c.codec.EncodeMsg(msgControlPing, c.pingReqID)
115 log.WithFields(logger.Fields{
118 "msg_id": c.pingReqID,
119 "msg_size": len(pingData),
120 "seq_num": req.seqNum,
121 }).Debug(" -> Sending a control ping to VPP.")
123 if err := c.vpp.SendMsg(context, pingData); err != nil {
124 log.WithFields(logger.Fields{
127 "seq_num": req.seqNum,
128 }).Warnf("unable to send control ping: %v", err)
135 // msgCallback is called whenever any binary API message comes from VPP.
136 func (c *Connection) msgCallback(msgID uint16, data []byte) {
138 defer connLock.RUnlock()
141 log.Warn("Already disconnected, ignoring the message.")
145 msg, ok := c.msgMap[msgID]
147 log.Warnf("Unknown message received, ID: %d", msgID)
151 // decode message context to fix for special cases of messages,
153 // - replies that don't have context as first field (comes as zero)
154 // - events that don't have context at all (comes as non zero)
156 context, err := c.codec.DecodeMsgContext(data, msg)
158 log.Errorf("decoding context failed: %v", err)
161 chanID, isMulti, seqNum := unpackRequestContext(context)
162 if log.Level == logger.DebugLevel { // for performance reasons - logrus does some processing even if debugs are disabled
163 log.WithFields(logger.Fields{
166 "msg_name": msg.GetMessageName(),
167 "msg_size": len(data),
171 }).Debug(" <- Received a message from VPP.")
174 if context == 0 || c.isNotificationMessage(msgID) {
175 // process the message as a notification
176 c.sendNotifications(msgID, data)
180 // match ch according to the context
181 c.channelsLock.RLock()
182 ch, ok := c.channels[chanID]
183 c.channelsLock.RUnlock()
185 log.WithFields(logger.Fields{
188 }).Error("Channel ID not known, ignoring the message.")
192 // if this is a control ping reply to a multipart request,
193 // treat this as a last part of the reply
194 lastReplyReceived := isMulti && msgID == c.pingReplyID
196 // send the data to the channel, it needs to be copied,
197 // because it will be freed after this function returns
198 sendReply(ch, &vppReply{
201 data: append([]byte(nil), data...),
202 lastReceived: lastReplyReceived,
205 // store actual time of this reply
206 c.lastReplyLock.Lock()
207 c.lastReply = time.Now()
208 c.lastReplyLock.Unlock()
211 // sendReply sends the reply into the go channel, if it cannot be completed without blocking, otherwise
212 // it logs the error and do not send the message.
213 func sendReply(ch *Channel, reply *vppReply) {
215 case ch.replyChan <- reply:
216 // reply sent successfully
217 case <-time.After(time.Millisecond * 100):
218 // receiver still not ready
219 log.WithFields(logger.Fields{
221 "msg_id": reply.msgID,
222 "seq_num": reply.seqNum,
223 }).Warn("Unable to send the reply, reciever end not ready.")
227 func sendReplyError(ch *Channel, req *vppRequest, err error) {
228 sendReply(ch, &vppReply{seqNum: req.seqNum, err: err})
231 // isNotificationMessage returns true if someone has subscribed to provided message ID.
232 func (c *Connection) isNotificationMessage(msgID uint16) bool {
233 c.subscriptionsLock.RLock()
234 defer c.subscriptionsLock.RUnlock()
236 _, exists := c.subscriptions[msgID]
240 // sendNotifications send a notification message to all subscribers subscribed for that message.
241 func (c *Connection) sendNotifications(msgID uint16, data []byte) {
242 c.subscriptionsLock.RLock()
243 defer c.subscriptionsLock.RUnlock()
247 // send to notification to each subscriber
248 for _, sub := range c.subscriptions[msgID] {
249 log.WithFields(logger.Fields{
250 "msg_name": sub.event.GetMessageName(),
252 "msg_size": len(data),
253 }).Debug("Sending a notification to the subscription channel.")
255 event := sub.msgFactory()
256 if err := c.codec.DecodeMsg(data, event); err != nil {
257 log.WithFields(logger.Fields{
258 "msg_name": sub.event.GetMessageName(),
260 "msg_size": len(data),
261 }).Errorf("Unable to decode the notification message: %v", err)
265 // send the message into the go channel of the subscription
267 case sub.notifChan <- event:
268 // message sent successfully
270 // unable to write into the channel without blocking
271 log.WithFields(logger.Fields{
272 "msg_name": sub.event.GetMessageName(),
274 "msg_size": len(data),
275 }).Warn("Unable to deliver the notification, reciever end not ready.")
282 log.WithFields(logger.Fields{
284 "msg_size": len(data),
285 }).Info("No subscription found for the notification message.")
289 // +------------------+-------------------+-----------------------+
290 // | 15b = channel ID | 1b = is multipart | 16b = sequence number |
291 // +------------------+-------------------+-----------------------+
292 func packRequestContext(chanID uint16, isMultipart bool, seqNum uint16) uint32 {
293 context := uint32(chanID) << 17
297 context |= uint32(seqNum)
301 func unpackRequestContext(context uint32) (chanID uint16, isMulipart bool, seqNum uint16) {
302 chanID = uint16(context >> 17)
303 if ((context >> 16) & 0x1) != 0 {
306 seqNum = uint16(context & 0xffff)
310 // compareSeqNumbers returns -1, 0, 1 if sequence number <seqNum1> precedes, equals to,
311 // or succeeds seq. number <seqNum2>.
312 // Since sequence numbers cycle in the finite set of size 2^16, the function
313 // must assume that the distance between compared sequence numbers is less than
314 // (2^16)/2 to determine the order.
315 func compareSeqNumbers(seqNum1, seqNum2 uint16) int {
316 // calculate distance from seqNum1 to seqNum2
318 if seqNum1 <= seqNum2 {
319 dist = seqNum2 - seqNum1
321 dist = 0xffff - (seqNum1 - seqNum2 - 1)
325 } else if dist <= 0x8000 {