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