1 // Copyright (c) 2017 Cisco and/or its affiliates.
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:
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 // Package mock is an alternative VPP adapter aimed for unit/integration testing where the
16 // actual communication with VPP is not demanded.
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"
36 useRepliesQueue // use replies in the queue
37 useReplyHandlers // use reply handler
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
46 msgNameToIds map[string]uint16
47 msgIDsToName map[uint16]string
48 binAPITypes map[string]reflect.Type
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
56 // defaultReply is a default reply message that mock adapter returns for a request.
57 type defaultReply struct {
61 // MessageDTO is a structure used for propagating information to ReplyHandlers.
62 type MessageDTO struct {
69 // reply for one request (can be multipart, contain replies to previously timeouted requests, etc.)
74 // MsgWithContext encapsulates reply message with possibly sequence number and is-multipart flag.
75 type MsgWithContext struct {
80 /* set by mock adapter */
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)
89 defaultReplyMsgID = 1 // default message ID for the reply to be sent back via callback
92 // NewVppAdapter returns a new mock adapter.
93 func NewVppAdapter() *VppAdapter {
95 msgIDsToName: make(map[uint16]string),
96 msgNameToIds: make(map[string]uint16),
98 binAPITypes: make(map[string]reflect.Type),
100 a.registerBinAPITypes()
104 // Connect emulates connecting the process to VPP.
105 func (a *VppAdapter) Connect() error {
109 // Disconnect emulates disconnecting the process from VPP.
110 func (a *VppAdapter) Disconnect() {
114 // GetMsgNameByID returns message name for specified message ID.
115 func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
118 return "control_ping", true
120 return "control_ping_reply", true
122 return "sw_interface_dump", true
124 return "sw_interface_details", true
128 defer a.access.Unlock()
129 msgName, found := a.msgIDsToName[msgID]
131 return msgName, found
134 func (a *VppAdapter) registerBinAPITypes() {
136 defer a.access.Unlock()
137 for _, msg := range api.GetAllMessages() {
138 a.binAPITypes[msg.GetMessageName()] = reflect.TypeOf(msg).Elem()
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)
146 if reply, found := a.binAPITypes[replyName]; found {
147 msgID, err := a.GetMsgID(replyName, "")
149 return reply, msgID, found
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)
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
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())
175 log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
179 log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
181 buf := new(bytes.Buffer)
182 err = struc.Pack(buf, &codec.VppReplyHeader{
184 Context: request.ClientID,
189 err = struc.Pack(buf, reply)
194 return buf.Bytes(), nil
197 // GetMsgID returns mocked message ID for the given message name and CRC.
198 func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
202 case "control_ping_reply":
204 case "sw_interface_dump":
206 case "sw_interface_details":
211 defer a.access.Unlock()
213 msgID, found := a.msgNameToIds[msgName]
220 a.msgNameToIds[msgName] = msgID
221 a.msgIDsToName[msgID] = msgName
226 // SendMsg emulates sending a binary-encoded message to VPP.
227 func (a *VppAdapter) SendMsg(clientID uint32, data []byte) error {
229 case useReplyHandlers:
230 for i := len(a.replyHandlers) - 1; i >= 0; i-- {
231 replyHandler := a.replyHandlers[i]
233 buf := bytes.NewReader(data)
234 reqHeader := codec.VppRequestHeader{}
235 struc.Unpack(buf, &reqHeader)
238 reqMsgName := a.msgIDsToName[reqHeader.VlMsgID]
241 reply, msgID, finished := replyHandler(MessageDTO{
242 MsgID: reqHeader.VlMsgID,
248 a.callback(msgID, clientID, reply)
254 case useRepliesQueue:
256 defer a.repliesLock.Unlock()
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)
266 context = setMultipart(context, msg.Multipart)
267 context = setSeqNum(context, msg.SeqNum)
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})
276 struc.Pack(buf, &codec.VppOtherHeader{VlMsgID: msgID})
278 struc.Pack(buf, msg.Msg)
279 a.callback(msgID, context, buf.Bytes())
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
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())
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) {
308 // WaitReady mocks waiting for VPP
309 func (a *VppAdapter) WaitReady() error {
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.
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.
325 // mockVpp.MockReply( // push multipart messages all at once
326 // &interfaces.SwInterfaceDetails{SwIfIndex:1},
327 // &interfaces.SwInterfaceDetails{SwIfIndex:2},
328 // &interfaces.SwInterfaceDetails{SwIfIndex:3},
330 // mockVpp.MockReply(&vpe.ControlPingReply{})
332 // Even if the multipart request has no replies, MockReply has to be called twice:
334 // mockVpp.MockReply() // zero multipart messages
335 // mockVpp.MockReply(&vpe.ControlPingReply{})
336 func (a *VppAdapter) MockReply(msgs ...api.Message) {
338 defer a.repliesLock.Unlock()
341 for _, msg := range msgs {
342 r.msgs = append(r.msgs, MsgWithContext{Msg: msg, hasCtx: false})
344 a.replies = append(a.replies, r)
345 a.mode = useRepliesQueue
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) {
355 defer a.repliesLock.Unlock()
358 for _, msg := range msgs {
359 r.msgs = append(r.msgs,
360 MsgWithContext{Msg: msg.Msg, SeqNum: msg.SeqNum, Multipart: msg.Multipart, hasCtx: true})
362 a.replies = append(a.replies, r)
363 a.mode = useRepliesQueue
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) {
370 defer a.repliesLock.Unlock()
372 a.replyHandlers = append(a.replyHandlers, replyHandler)
373 a.mode = useReplyHandlers
376 func setSeqNum(context uint32, seqNum uint16) (newContext uint32) {
377 context &= 0xffff0000
378 context |= uint32(seqNum)
382 func setMultipart(context uint32, isMultipart bool) (newContext uint32) {
383 context &= 0xfffeffff