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