initial commit
[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         "github.com/lunixbochs/struc"
26
27         "gerrit.fd.io/r/govpp/adapter"
28         "gerrit.fd.io/r/govpp/adapter/mock/binapi_reflect"
29         "gerrit.fd.io/r/govpp/api"
30 )
31
32 // VppAdapter represents a mock VPP adapter that can be used for unit/integration testing instead of the vppapiclient adapter.
33 type VppAdapter struct {
34         callback func(context uint32, msgId uint16, data []byte)
35
36         msgNameToIds *map[string]uint16
37         msgIdsToName *map[uint16]string
38         msgIdSeq     uint16
39         binApiTypes  map[string]reflect.Type
40         //TODO lock
41 }
42
43 // replyHeader represents a common header of each VPP request message.
44 type requestHeader struct {
45         VlMsgID     uint16
46         ClientIndex uint32
47         Context     uint32
48 }
49
50 // replyHeader represents a common header of each VPP reply message.
51 type replyHeader struct {
52         VlMsgID uint16
53         Context uint32
54 }
55
56 // replyHeader represents a common header of each VPP reply message.
57 type vppOtherHeader struct {
58         VlMsgID uint16
59 }
60
61 // defaultReply is a default reply message that mock adapter returns for a request.
62 type defaultReply struct {
63         Retval int32
64 }
65
66 // MessageDTO is a structure used for propageating informations to ReplyHandlers
67 type MessageDTO struct {
68         MsgID    uint16
69         MsgName  string
70         ClientID uint32
71         Data     []byte
72 }
73
74 // ReplyHandler is a type that allows to extend the behaviour of VPP mock.
75 // Return value prepared is used to signalize that mock reply is calculated.
76 type ReplyHandler func(request MessageDTO) (reply []byte, msgID uint16, prepared bool)
77
78 const (
79         //defaultMsgID      = 1 // default message ID to be returned from GetMsgId
80         defaultReplyMsgID = 2 // default message ID for the reply to be sent back via callback
81 )
82
83 var replies []api.Message        // FIFO queue of messages
84 var replyHandlers []ReplyHandler // callbacks that are able to calculate mock responses
85 var repliesLock sync.Mutex       // mutex for the queue
86 var mode = 0
87
88 const useRepliesQueue = 1  // use replies in the queue instead of the default one
89 const useReplyHandlers = 2 //use ReplyHandler
90
91 // NewVppAdapter returns a new mock adapter.
92 func NewVppAdapter() adapter.VppAdapter {
93         return &VppAdapter{}
94 }
95
96 // Connect emulates connecting the process to VPP.
97 func (a *VppAdapter) Connect() error {
98         return nil
99 }
100
101 // Disconnect emulates disconnecting the process from VPP.
102 func (a *VppAdapter) Disconnect() {
103         // no op
104 }
105
106 func (a *VppAdapter) GetMsgNameByID(msgId uint16) (string, bool) {
107         a.initMaps()
108
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         msgName, found := (*a.msgIdsToName)[msgId]
121
122         return msgName, found
123 }
124
125 func (a *VppAdapter) RegisterBinApiTypes(binApiTypes map[string]reflect.Type) {
126         a.initMaps()
127         for _, v := range binApiTypes {
128                 if msg, ok := reflect.New(v).Interface().(api.Message); ok {
129                         a.binApiTypes[msg.GetMessageName()] = v
130                 }
131         }
132 }
133
134 func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
135         replyName, foundName := binapi_reflect.ReplyNameFor(requestMsgName)
136         if foundName {
137                 if reply, found := a.binApiTypes[replyName]; found {
138                         msgID, err := a.GetMsgID(replyName, "")
139                         if err == nil {
140                                 return reply, msgID, found
141                         }
142                 }
143         }
144
145         return nil, 0, false
146 }
147
148 func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
149         replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
150         if foundReplType {
151                 msgVal := reflect.New(replType)
152                 if msg, ok := msgVal.Interface().(api.Message); ok {
153                         log.Println("FFF ", replType, msgID, foundReplType)
154                         return msg, msgID, true
155                 }
156         }
157
158         return nil, 0, false
159 }
160
161 func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
162         replyMsgId, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
163         if err != nil {
164                 log.Println("ReplyBytesE ", replyMsgId, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
165                         " ", err)
166                 return nil, err
167         }
168         log.Println("ReplyBytes ", replyMsgId, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
169
170         buf := new(bytes.Buffer)
171         struc.Pack(buf, &replyHeader{VlMsgID: replyMsgId, Context: request.ClientID})
172         struc.Pack(buf, reply)
173
174         return buf.Bytes(), nil
175 }
176
177 // GetMsgID returns mocked message ID for the given message name and CRC.
178 func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
179         switch msgName {
180         case "control_ping":
181                 return 100, nil
182         case "control_ping_reply":
183                 return 101, nil
184         case "sw_interface_dump":
185                 return 200, nil
186         case "sw_interface_details":
187                 return 201, nil
188         }
189
190         a.initMaps()
191
192         if msgId, found := (*a.msgNameToIds)[msgName]; found {
193                 return msgId, nil
194         } else {
195                 a.msgIdSeq++
196                 msgId = a.msgIdSeq
197                 (*a.msgNameToIds)[msgName] = msgId
198                 (*a.msgIdsToName)[msgId] = msgName
199
200                 log.Println("VPP GetMessageId ", msgId, " name:", msgName, " crc:", msgCrc)
201
202                 return msgId, nil
203         }
204 }
205
206 func (a *VppAdapter) initMaps() {
207         if a.msgIdsToName == nil {
208                 a.msgIdsToName = &map[uint16]string{}
209                 a.msgNameToIds = &map[string]uint16{}
210                 a.msgIdSeq = 1000
211         }
212
213         if a.binApiTypes == nil {
214                 a.binApiTypes = map[string]reflect.Type{}
215         }
216 }
217
218 // SendMsg emulates sending a binary-encoded message to VPP.
219 func (a *VppAdapter) SendMsg(clientID uint32, data []byte) error {
220         switch mode {
221         case useReplyHandlers:
222                 for i := len(replyHandlers) - 1; i >= 0; i-- {
223                         replyHandler := replyHandlers[i]
224
225                         buf := bytes.NewReader(data)
226                         reqHeader := requestHeader{}
227                         struc.Unpack(buf, &reqHeader)
228
229                         a.initMaps()
230                         reqMsgName, _ := (*a.msgIdsToName)[reqHeader.VlMsgID]
231
232                         reply, msgID, finished := replyHandler(MessageDTO{reqHeader.VlMsgID, reqMsgName,
233                                 clientID, data})
234                         if finished {
235                                 a.callback(clientID, msgID, reply)
236                                 return nil
237                         }
238                 }
239                 fallthrough
240         case useRepliesQueue:
241                 repliesLock.Lock()
242                 defer repliesLock.Unlock()
243
244                 // pop all replies from queue
245                 for i, reply := range replies {
246                         if i > 0 && reply.GetMessageName() == "control_ping_reply" {
247                                 // hack - do not send control_ping_reply immediately, leave it for the the next callback
248                                 replies = []api.Message{}
249                                 replies = append(replies, reply)
250                                 return nil
251                         }
252                         msgID, _ := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
253                         buf := new(bytes.Buffer)
254                         if reply.GetMessageType() == api.ReplyMessage {
255                                 struc.Pack(buf, &replyHeader{VlMsgID: msgID, Context: clientID})
256                         } else {
257                                 struc.Pack(buf, &requestHeader{VlMsgID: msgID, Context: clientID})
258                         }
259                         struc.Pack(buf, reply)
260                         a.callback(clientID, msgID, buf.Bytes())
261                 }
262                 if len(replies) > 0 {
263                         replies = []api.Message{}
264                         return nil
265                 }
266
267                 //fallthrough
268         default:
269                 // return default reply
270                 buf := new(bytes.Buffer)
271                 msgID := uint16(defaultReplyMsgID)
272                 struc.Pack(buf, &replyHeader{VlMsgID: msgID, Context: clientID})
273                 struc.Pack(buf, &defaultReply{})
274                 a.callback(clientID, msgID, buf.Bytes())
275         }
276         return nil
277 }
278
279 // SetMsgCallback sets a callback function that will be called by the adapter whenever a message comes from the mock.
280 func (a *VppAdapter) SetMsgCallback(cb func(context uint32, msgID uint16, data []byte)) {
281         a.callback = cb
282 }
283
284 // MockReply stores a message to be returned when the next request comes. It is a FIFO queue - multiple replies
285 // can be pushed into it, the first one will be popped when some request comes.
286 //
287 // It is able to also receive callback that calculates the reply
288 func (a *VppAdapter) MockReply(msg api.Message) {
289         repliesLock.Lock()
290         defer repliesLock.Unlock()
291
292         replies = append(replies, msg)
293         mode = useRepliesQueue
294 }
295
296 func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
297         repliesLock.Lock()
298         defer repliesLock.Unlock()
299
300         replyHandlers = append(replyHandlers, replyHandler)
301         mode = useReplyHandlers
302 }