f79bb8bffdace6902db70c81bfe6a173188c2bc1
[govpp.git] / adapter / mock / mock_vpp_adapter.go
1 // Copyright (c) 2017 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 mock is an alternative VPP adapter aimed for unit/integration testing where the
16 // actual communication with VPP is not demanded.
17 package mock
18
19 import (
20         "encoding/binary"
21         "log"
22         "reflect"
23         "sync"
24
25         "git.fd.io/govpp.git/adapter"
26         "git.fd.io/govpp.git/adapter/mock/binapi"
27         "git.fd.io/govpp.git/api"
28         "git.fd.io/govpp.git/codec"
29 )
30
31 type replyMode int
32
33 const (
34         _                replyMode = iota
35         useRepliesQueue            // use replies in the queue
36         useReplyHandlers           // use reply handler
37 )
38
39 // VppAPI represents a mock VPP adapter that can be used for unit/integration testing instead of the vppapiclient adapter.
40 type VppAdapter struct {
41         callback adapter.MsgCallback
42
43         msgIDSeq     uint16
44         access       sync.RWMutex
45         msgNameToIds map[string]uint16
46         msgIDsToName map[uint16]string
47         binAPITypes  map[string]reflect.Type
48
49         repliesLock   sync.Mutex     // mutex for the queue
50         replies       []reply        // FIFO queue of messages
51         replyHandlers []ReplyHandler // callbacks that are able to calculate mock responses
52         mode          replyMode      // mode in which the mock operates
53 }
54
55 // defaultReply is a default reply message that mock adapter returns for a request.
56 type defaultReply struct {
57         Retval int32
58 }
59
60 func (*defaultReply) GetMessageName() string { return "mock_default_reply" }
61 func (*defaultReply) GetCrcString() string   { return "xxxxxxxx" }
62 func (*defaultReply) GetMessageType() api.MessageType {
63         return api.ReplyMessage
64 }
65 func (m *defaultReply) Size() int {
66         if m == nil {
67                 return 0
68         }
69         var size int
70         // field[1] m.Retval
71         size += 4
72         return size
73 }
74 func (m *defaultReply) Marshal(b []byte) ([]byte, error) {
75         var buf *codec.Buffer
76         if b == nil {
77                 buf = codec.NewBuffer(make([]byte, m.Size()))
78         } else {
79                 buf = codec.NewBuffer(b)
80         }
81         // field[1] m.Retval
82         buf.EncodeUint32(uint32(m.Retval))
83         return buf.Bytes(), nil
84 }
85 func (m *defaultReply) Unmarshal(b []byte) error {
86         buf := codec.NewBuffer(b)
87         // field[1] m.Retval
88         m.Retval = int32(buf.DecodeUint32())
89         return nil
90 }
91
92 // MessageDTO is a structure used for propagating information to ReplyHandlers.
93 type MessageDTO struct {
94         MsgID    uint16
95         MsgName  string
96         ClientID uint32
97         Data     []byte
98 }
99
100 // reply for one request (can be multipart, contain replies to previously timeouted requests, etc.)
101 type reply struct {
102         msgs []MsgWithContext
103 }
104
105 // MsgWithContext encapsulates reply message with possibly sequence number and is-multipart flag.
106 type MsgWithContext struct {
107         Msg       api.Message
108         SeqNum    uint16
109         Multipart bool
110
111         /* set by mock adapter */
112         hasCtx bool
113 }
114
115 // ReplyHandler is a type that allows to extend the behaviour of VPP mock.
116 // Return value ok is used to signalize that mock reply is calculated and ready to be used.
117 type ReplyHandler func(request MessageDTO) (reply []byte, msgID uint16, ok bool)
118
119 const (
120         defaultReplyMsgID = 1 // default message ID for the reply to be sent back via callback
121 )
122
123 // NewVppAdapter returns a new mock adapter.
124 func NewVppAdapter() *VppAdapter {
125         a := &VppAdapter{
126                 msgIDSeq:     1000,
127                 msgIDsToName: make(map[uint16]string),
128                 msgNameToIds: make(map[string]uint16),
129                 binAPITypes:  make(map[string]reflect.Type),
130         }
131         a.registerBinAPITypes()
132         return a
133 }
134
135 // Connect emulates connecting the process to VPP.
136 func (a *VppAdapter) Connect() error {
137         return nil
138 }
139
140 // Disconnect emulates disconnecting the process from VPP.
141 func (a *VppAdapter) Disconnect() error {
142         return nil
143 }
144
145 // GetMsgNameByID returns message name for specified message ID.
146 func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
147         switch msgID {
148         case 100:
149                 return "control_ping", true
150         case 101:
151                 return "control_ping_reply", true
152         case 200:
153                 return "sw_interface_dump", true
154         case 201:
155                 return "sw_interface_details", true
156         }
157
158         a.access.Lock()
159         defer a.access.Unlock()
160         msgName, found := a.msgIDsToName[msgID]
161
162         return msgName, found
163 }
164
165 func (a *VppAdapter) registerBinAPITypes() {
166         a.access.Lock()
167         defer a.access.Unlock()
168         for _, msg := range api.GetRegisteredMessages() {
169                 a.binAPITypes[msg.GetMessageName()] = reflect.TypeOf(msg).Elem()
170         }
171 }
172
173 // ReplyTypeFor returns reply message type for given request message name.
174 func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
175         replyName, foundName := binapi.ReplyNameFor(requestMsgName)
176         if foundName {
177                 if reply, found := a.binAPITypes[replyName]; found {
178                         msgID, err := a.GetMsgID(replyName, "")
179                         if err == nil {
180                                 return reply, msgID, found
181                         }
182                 }
183         }
184
185         return nil, 0, false
186 }
187
188 // ReplyFor returns reply message for given request message name.
189 func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
190         replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
191         if foundReplType {
192                 msgVal := reflect.New(replType)
193                 if msg, ok := msgVal.Interface().(api.Message); ok {
194                         log.Println("FFF ", replType, msgID, foundReplType)
195                         return msg, msgID, true
196                 }
197         }
198
199         return nil, 0, false
200 }
201
202 // ReplyBytes encodes the mocked reply into binary format.
203 func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
204         replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
205         if err != nil {
206                 log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
207                         " ", err)
208                 return nil, err
209         }
210         log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
211
212         data, err := codec.DefaultCodec.EncodeMsg(reply, replyMsgID)
213         if err != nil {
214                 return nil, err
215         }
216         if reply.GetMessageType() == api.ReplyMessage {
217                 binary.BigEndian.PutUint32(data[2:6], request.ClientID)
218         } else if reply.GetMessageType() == api.RequestMessage {
219                 binary.BigEndian.PutUint32(data[6:10], request.ClientID)
220         }
221         return data, nil
222 }
223
224 // GetMsgID returns mocked message ID for the given message name and CRC.
225 func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
226         switch msgName {
227         case "control_ping":
228                 return 100, nil
229         case "control_ping_reply":
230                 return 101, nil
231         case "sw_interface_dump":
232                 return 200, nil
233         case "sw_interface_details":
234                 return 201, nil
235         }
236
237         a.access.Lock()
238         defer a.access.Unlock()
239
240         msgID, found := a.msgNameToIds[msgName]
241         if found {
242                 return msgID, nil
243         }
244
245         a.msgIDSeq++
246         msgID = a.msgIDSeq
247         a.msgNameToIds[msgName] = msgID
248         a.msgIDsToName[msgID] = msgName
249
250         return msgID, nil
251 }
252
253 // SendMsg emulates sending a binary-encoded message to VPP.
254 func (a *VppAdapter) SendMsg(clientID uint32, data []byte) error {
255         a.repliesLock.Lock()
256         mode := a.mode
257         a.repliesLock.Unlock()
258         switch mode {
259         case useReplyHandlers:
260                 for i := len(a.replyHandlers) - 1; i >= 0; i-- {
261                         replyHandler := a.replyHandlers[i]
262
263                         msgID := binary.BigEndian.Uint16(data[0:2])
264
265                         a.access.Lock()
266                         reqMsgName := a.msgIDsToName[msgID]
267                         a.access.Unlock()
268
269                         reply, msgID, finished := replyHandler(MessageDTO{
270                                 MsgID:    msgID,
271                                 MsgName:  reqMsgName,
272                                 ClientID: clientID,
273                                 Data:     data,
274                         })
275                         if finished {
276                                 a.callback(msgID, reply)
277                                 return nil
278                         }
279                 }
280                 fallthrough
281
282         case useRepliesQueue:
283                 a.repliesLock.Lock()
284                 defer a.repliesLock.Unlock()
285
286                 // pop the first reply
287                 if len(a.replies) > 0 {
288                         reply := a.replies[0]
289                         for _, msg := range reply.msgs {
290                                 msgID, _ := a.GetMsgID(msg.Msg.GetMessageName(), msg.Msg.GetCrcString())
291                                 context := clientID
292                                 if msg.hasCtx {
293                                         context = setMultipart(context, msg.Multipart)
294                                         context = setSeqNum(context, msg.SeqNum)
295                                 }
296                                 data, err := codec.DefaultCodec.EncodeMsg(msg.Msg, msgID)
297                                 if err != nil {
298                                         panic(err)
299                                 }
300                                 if msg.Msg.GetMessageType() == api.ReplyMessage {
301                                         binary.BigEndian.PutUint32(data[2:6], context)
302                                 } else if msg.Msg.GetMessageType() == api.RequestMessage {
303                                         binary.BigEndian.PutUint32(data[6:10], context)
304                                 }
305                                 a.callback(msgID, data)
306                         }
307
308                         a.replies = a.replies[1:]
309                         if len(a.replies) == 0 && len(a.replyHandlers) > 0 {
310                                 // Switch back to handlers once the queue is empty to revert back
311                                 // the fallthrough effect.
312                                 a.mode = useReplyHandlers
313                         }
314                         return nil
315                 }
316
317                 //fallthrough
318         default:
319                 // return default reply
320                 msgID := uint16(defaultReplyMsgID)
321                 data, err := codec.DefaultCodec.EncodeMsg(&defaultReply{}, msgID)
322                 if err != nil {
323                         panic(err)
324                 }
325                 binary.BigEndian.PutUint32(data[2:6], clientID)
326                 a.callback(msgID, data)
327         }
328         return nil
329 }
330
331 // SetMsgCallback sets a callback function that will be called by the adapter whenever a message comes from the mock.
332 func (a *VppAdapter) SetMsgCallback(cb adapter.MsgCallback) {
333         a.callback = cb
334 }
335
336 // WaitReady mocks waiting for VPP
337 func (a *VppAdapter) WaitReady() error {
338         return nil
339 }
340
341 // MockReply stores a message or a list of multipart messages to be returned when
342 // the next request comes. It is a FIFO queue - multiple replies can be pushed into it,
343 // the first message or the first set of multi-part messages will be popped when
344 // some request comes.
345 // Using of this method automatically switches the mock into the useRepliesQueue mode.
346 //
347 // Note: multipart requests are implemented using two requests actually - the multipart
348 // request itself followed by control ping used to tell which multipart message
349 // is the last one. A mock reply to a multipart request has to thus consist of
350 // exactly two calls of this method.
351 // For example:
352 //
353 //    mockVpp.MockReply(  // push multipart messages all at once
354 //                      &interfaces.SwInterfaceDetails{SwIfIndex:1},
355 //                      &interfaces.SwInterfaceDetails{SwIfIndex:2},
356 //                      &interfaces.SwInterfaceDetails{SwIfIndex:3},
357 //    )
358 //    mockVpp.MockReply(&vpe.ControlPingReply{})
359 //
360 // Even if the multipart request has no replies, MockReply has to be called twice:
361 //
362 //    mockVpp.MockReply()  // zero multipart messages
363 //    mockVpp.MockReply(&vpe.ControlPingReply{})
364 func (a *VppAdapter) MockReply(msgs ...api.Message) {
365         a.repliesLock.Lock()
366         defer a.repliesLock.Unlock()
367
368         r := reply{}
369         for _, msg := range msgs {
370                 r.msgs = append(r.msgs, MsgWithContext{Msg: msg, hasCtx: false})
371         }
372         a.replies = append(a.replies, r)
373         a.mode = useRepliesQueue
374 }
375
376 // MockReplyWithContext queues next reply like MockReply() does, except that the
377 // sequence number and multipart flag (= context minus channel ID) can be customized
378 // and not necessarily match with the request.
379 // The purpose of this function is to test handling of sequence numbers and as such
380 // it is not really meant to be used outside the govpp UTs.
381 func (a *VppAdapter) MockReplyWithContext(msgs ...MsgWithContext) {
382         a.repliesLock.Lock()
383         defer a.repliesLock.Unlock()
384
385         r := reply{}
386         for _, msg := range msgs {
387                 r.msgs = append(r.msgs,
388                         MsgWithContext{Msg: msg.Msg, SeqNum: msg.SeqNum, Multipart: msg.Multipart, hasCtx: true})
389         }
390         a.replies = append(a.replies, r)
391         a.mode = useRepliesQueue
392 }
393
394 // MockReplyHandler registers a handler function that is supposed to generate mock responses to incoming requests.
395 // Using of this method automatically switches the mock into th useReplyHandlers mode.
396 func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
397         a.repliesLock.Lock()
398         defer a.repliesLock.Unlock()
399
400         a.replyHandlers = append(a.replyHandlers, replyHandler)
401         a.mode = useReplyHandlers
402 }
403
404 // MockClearReplyHanders clears all reply handlers that were registered
405 // Will also set the mode to useReplyHandlers
406 func (a *VppAdapter) MockClearReplyHandlers() {
407         a.repliesLock.Lock()
408         defer a.repliesLock.Unlock()
409
410         a.replyHandlers = a.replyHandlers[:0]
411         a.mode = useReplyHandlers
412 }
413
414 func setSeqNum(context uint32, seqNum uint16) (newContext uint32) {
415         context &= 0xffff0000
416         context |= uint32(seqNum)
417         return context
418 }
419
420 func setMultipart(context uint32, isMultipart bool) (newContext uint32) {
421         context &= 0xfffeffff
422         if isMultipart {
423                 context |= 1 << 16
424         }
425         return context
426 }