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