Decode message context using the message type only
[govpp.git] / core / channel.go
1 // Copyright (c) 2018 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 core
16
17 import (
18         "errors"
19         "fmt"
20         "reflect"
21         "strings"
22         "time"
23
24         "github.com/sirupsen/logrus"
25
26         "git.fd.io/govpp.git/adapter"
27         "git.fd.io/govpp.git/api"
28 )
29
30 var (
31         ErrInvalidRequestCtx = errors.New("invalid request context")
32 )
33
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
40         // DecodeMsgContext decodes context from message data and type.
41         DecodeMsgContext(data []byte, msgType api.MessageType) (context uint32, err error)
42 }
43
44 // MessageIdentifier provides identification of generated API messages.
45 type MessageIdentifier interface {
46         // GetMessageID returns message identifier of given API message.
47         GetMessageID(msg api.Message) (uint16, error)
48         // GetMessagePath returns path for the given message
49         GetMessagePath(msg api.Message) string
50         // LookupByID looks up message name and crc by ID
51         LookupByID(path string, msgID uint16) (api.Message, error)
52 }
53
54 // vppRequest is a request that will be sent to VPP.
55 type vppRequest struct {
56         seqNum uint16      // sequence number
57         msg    api.Message // binary API message to be send to VPP
58         multi  bool        // true if multipart response is expected
59 }
60
61 // vppReply is a reply received from VPP.
62 type vppReply struct {
63         seqNum       uint16 // sequence number
64         msgID        uint16 // ID of the message
65         data         []byte // encoded data with the message
66         lastReceived bool   // for multi request, true if the last reply has been already received
67         err          error  // in case of error, data is nil and this member contains error
68 }
69
70 // requestCtx is a context for request with single reply
71 type requestCtx struct {
72         ch     *Channel
73         seqNum uint16
74 }
75
76 // multiRequestCtx is a context for request with multiple responses
77 type multiRequestCtx struct {
78         ch     *Channel
79         seqNum uint16
80 }
81
82 // subscriptionCtx is a context of subscription for delivery of specific notification messages.
83 type subscriptionCtx struct {
84         ch         *Channel
85         notifChan  chan api.Message   // channel where notification messages will be delivered to
86         msgID      uint16             // message ID for the subscribed event message
87         event      api.Message        // event message that this subscription is for
88         msgFactory func() api.Message // function that returns a new instance of the specific message that is expected as a notification
89 }
90
91 // Channel is the main communication interface with govpp core. It contains four Go channels, one for sending the requests
92 // to VPP, one for receiving the replies from it and the same set for notifications. The user can access the Go channels
93 // via methods provided by Channel interface in this package. Do not use the same channel from multiple goroutines
94 // concurrently, otherwise the responses could mix! Use multiple channels instead.
95 type Channel struct {
96         id   uint16
97         conn *Connection
98
99         reqChan   chan *vppRequest // channel for sending the requests to VPP
100         replyChan chan *vppReply   // channel where VPP replies are delivered to
101
102         msgCodec      MessageCodec      // used to decode binary data to generated API messages
103         msgIdentifier MessageIdentifier // used to retrieve message ID of a message
104
105         lastSeqNum uint16 // sequence number of the last sent request
106
107         delayedReply        *vppReply     // reply already taken from ReplyChan, buffered for later delivery
108         replyTimeout        time.Duration // maximum time that the API waits for a reply from VPP before returning an error, can be set with SetReplyTimeout
109         receiveReplyTimeout time.Duration // maximum time that we wait for receiver to consume reply
110 }
111
112 func newChannel(id uint16, conn *Connection, codec MessageCodec, identifier MessageIdentifier, reqSize, replySize int) *Channel {
113         return &Channel{
114                 id:                  id,
115                 conn:                conn,
116                 msgCodec:            codec,
117                 msgIdentifier:       identifier,
118                 reqChan:             make(chan *vppRequest, reqSize),
119                 replyChan:           make(chan *vppReply, replySize),
120                 replyTimeout:        DefaultReplyTimeout,
121                 receiveReplyTimeout: ReplyChannelTimeout,
122         }
123 }
124
125 func (ch *Channel) GetID() uint16 {
126         return ch.id
127 }
128
129 func (ch *Channel) SendRequest(msg api.Message) api.RequestCtx {
130         req := ch.newRequest(msg, false)
131         ch.reqChan <- req
132         return &requestCtx{ch: ch, seqNum: req.seqNum}
133 }
134
135 func (ch *Channel) SendMultiRequest(msg api.Message) api.MultiRequestCtx {
136         req := ch.newRequest(msg, true)
137         ch.reqChan <- req
138         return &multiRequestCtx{ch: ch, seqNum: req.seqNum}
139 }
140
141 func (ch *Channel) nextSeqNum() uint16 {
142         ch.lastSeqNum++
143         return ch.lastSeqNum
144 }
145
146 func (ch *Channel) newRequest(msg api.Message, multi bool) *vppRequest {
147         return &vppRequest{
148                 msg:    msg,
149                 seqNum: ch.nextSeqNum(),
150                 multi:  multi,
151         }
152 }
153
154 func (ch *Channel) CheckCompatiblity(msgs ...api.Message) error {
155         var comperr api.CompatibilityError
156         for _, msg := range msgs {
157                 _, err := ch.msgIdentifier.GetMessageID(msg)
158                 if err != nil {
159                         if uerr, ok := err.(*adapter.UnknownMsgError); ok {
160                                 comperr.IncompatibleMessages = append(comperr.IncompatibleMessages, getMsgID(uerr.MsgName, uerr.MsgCrc))
161                                 continue
162                         }
163                         // other errors return immediatelly
164                         return err
165                 }
166                 comperr.CompatibleMessages = append(comperr.CompatibleMessages, getMsgNameWithCrc(msg))
167         }
168         if len(comperr.IncompatibleMessages) == 0 {
169                 return nil
170         }
171         return &comperr
172 }
173
174 func (ch *Channel) SubscribeNotification(notifChan chan api.Message, event api.Message) (api.SubscriptionCtx, error) {
175         msgID, err := ch.msgIdentifier.GetMessageID(event)
176         if err != nil {
177                 log.WithFields(logrus.Fields{
178                         "msg_name": event.GetMessageName(),
179                         "msg_crc":  event.GetCrcString(),
180                 }).Errorf("unable to retrieve message ID: %v", err)
181                 return nil, fmt.Errorf("unable to retrieve event message ID: %v", err)
182         }
183
184         sub := &subscriptionCtx{
185                 ch:         ch,
186                 notifChan:  notifChan,
187                 msgID:      msgID,
188                 event:      event,
189                 msgFactory: getMsgFactory(event),
190         }
191
192         // add the subscription into map
193         ch.conn.subscriptionsLock.Lock()
194         defer ch.conn.subscriptionsLock.Unlock()
195
196         ch.conn.subscriptions[msgID] = append(ch.conn.subscriptions[msgID], sub)
197
198         return sub, nil
199 }
200
201 func (ch *Channel) SetReplyTimeout(timeout time.Duration) {
202         ch.replyTimeout = timeout
203 }
204
205 func (ch *Channel) Close() {
206         close(ch.reqChan)
207 }
208
209 func (req *requestCtx) ReceiveReply(msg api.Message) error {
210         if req == nil || req.ch == nil {
211                 return ErrInvalidRequestCtx
212         }
213
214         lastReplyReceived, err := req.ch.receiveReplyInternal(msg, req.seqNum)
215         if err != nil {
216                 return err
217         } else if lastReplyReceived {
218                 return errors.New("multipart reply recieved while a single reply expected")
219         }
220
221         return nil
222 }
223
224 func (req *multiRequestCtx) ReceiveReply(msg api.Message) (lastReplyReceived bool, err error) {
225         if req == nil || req.ch == nil {
226                 return false, ErrInvalidRequestCtx
227         }
228
229         return req.ch.receiveReplyInternal(msg, req.seqNum)
230 }
231
232 func (sub *subscriptionCtx) Unsubscribe() error {
233         log.WithFields(logrus.Fields{
234                 "msg_name": sub.event.GetMessageName(),
235                 "msg_id":   sub.msgID,
236         }).Debug("Removing notification subscription.")
237
238         // remove the subscription from the map
239         sub.ch.conn.subscriptionsLock.Lock()
240         defer sub.ch.conn.subscriptionsLock.Unlock()
241
242         for i, item := range sub.ch.conn.subscriptions[sub.msgID] {
243                 if item == sub {
244                         // close notification channel
245                         close(sub.ch.conn.subscriptions[sub.msgID][i].notifChan)
246                         // remove i-th item in the slice
247                         sub.ch.conn.subscriptions[sub.msgID] = append(sub.ch.conn.subscriptions[sub.msgID][:i], sub.ch.conn.subscriptions[sub.msgID][i+1:]...)
248                         return nil
249                 }
250         }
251
252         return fmt.Errorf("subscription for %q not found", sub.event.GetMessageName())
253 }
254
255 // receiveReplyInternal receives a reply from the reply channel into the provided msg structure.
256 func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
257         if msg == nil {
258                 return false, errors.New("nil message passed in")
259         }
260
261         var ignore bool
262
263         if vppReply := ch.delayedReply; vppReply != nil {
264                 // try the delayed reply
265                 ch.delayedReply = nil
266                 ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
267                 if !ignore {
268                         return lastReplyReceived, err
269                 }
270         }
271
272         timer := time.NewTimer(ch.replyTimeout)
273         for {
274                 select {
275                 // blocks until a reply comes to ReplyChan or until timeout expires
276                 case vppReply := <-ch.replyChan:
277                         ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
278                         if ignore {
279                                 log.WithFields(logrus.Fields{
280                                         "expSeqNum": expSeqNum,
281                                         "channel":   ch.id,
282                                 }).Warnf("ignoring received reply: %+v (expecting: %s)", vppReply, msg.GetMessageName())
283                                 continue
284                         }
285                         return lastReplyReceived, err
286
287                 case <-timer.C:
288                         log.WithFields(logrus.Fields{
289                                 "expSeqNum": expSeqNum,
290                                 "channel":   ch.id,
291                         }).Debugf("timeout (%v) waiting for reply: %s", ch.replyTimeout, msg.GetMessageName())
292                         err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
293                         return false, err
294                 }
295         }
296 }
297
298 func (ch *Channel) processReply(reply *vppReply, expSeqNum uint16, msg api.Message) (ignore bool, lastReplyReceived bool, err error) {
299         // check the sequence number
300         cmpSeqNums := compareSeqNumbers(reply.seqNum, expSeqNum)
301         if cmpSeqNums == -1 {
302                 // reply received too late, ignore the message
303                 log.WithField("seqNum", reply.seqNum).
304                         Warn("Received reply to an already closed binary API request")
305                 ignore = true
306                 return
307         }
308         if cmpSeqNums == 1 {
309                 ch.delayedReply = reply
310                 err = fmt.Errorf("missing binary API reply with sequence number: %d", expSeqNum)
311                 return
312         }
313
314         if reply.err != nil {
315                 err = reply.err
316                 return
317         }
318         if reply.lastReceived {
319                 lastReplyReceived = true
320                 return
321         }
322
323         // message checks
324         var expMsgID uint16
325         expMsgID, err = ch.msgIdentifier.GetMessageID(msg)
326         if err != nil {
327                 err = fmt.Errorf("message %s with CRC %s is not compatible with the VPP we are connected to",
328                         msg.GetMessageName(), msg.GetCrcString())
329                 return
330         }
331
332         if reply.msgID != expMsgID {
333                 var msgNameCrc string
334                 pkgPath := ch.msgIdentifier.GetMessagePath(msg)
335                 if replyMsg, err := ch.msgIdentifier.LookupByID(pkgPath, reply.msgID); err != nil {
336                         msgNameCrc = err.Error()
337                 } else {
338                         msgNameCrc = getMsgNameWithCrc(replyMsg)
339                 }
340
341                 err = fmt.Errorf("received unexpected message (seqNum=%d), expected %s (ID %d), but got %s (ID %d) "+
342                         "(check if multiple goroutines are not sharing single GoVPP channel)",
343                         reply.seqNum, msg.GetMessageName(), expMsgID, msgNameCrc, reply.msgID)
344                 return
345         }
346
347         // decode the message
348         if err = ch.msgCodec.DecodeMsg(reply.data, msg); err != nil {
349                 return
350         }
351
352         // check Retval and convert it into VnetAPIError error
353         if strings.HasSuffix(msg.GetMessageName(), "_reply") {
354                 // TODO: use categories for messages to avoid checking message name
355                 if f := reflect.Indirect(reflect.ValueOf(msg)).FieldByName("Retval"); f.IsValid() {
356                         var retval int32
357                         switch f.Kind() {
358                         case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
359                                 retval = int32(f.Int())
360                         case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
361                                 retval = int32(f.Uint())
362                         default:
363                                 logrus.Warnf("invalid kind (%v) for Retval field of message %v", f.Kind(), msg.GetMessageName())
364                         }
365                         err = api.RetvalToVPPApiError(retval)
366                 }
367         }
368
369         return
370 }