blob: 312aa33557225d24d6ac86ad6f96e3ab80a34e77 [file] [log] [blame]
Ole Troana03f4ef2016-12-02 12:53:55 +01001#!/usr/bin/env python
Ole Troan5f9dcff2016-08-01 04:59:13 +02002#
3# Copyright (c) 2016 Cisco and/or its affiliates.
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at:
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
Ole Troana03f4ef2016-12-02 12:53:55 +010015#
Ole Troan5f9dcff2016-08-01 04:59:13 +020016
Ole Troan5f9dcff2016-08-01 04:59:13 +020017from __future__ import print_function
Ole Troana03f4ef2016-12-02 12:53:55 +010018import sys, os, logging, collections, struct, json, threading
19logging.basicConfig(level=logging.DEBUG)
Ole Troan5f9dcff2016-08-01 04:59:13 +020020import vpp_api
Ole Troan5f9dcff2016-08-01 04:59:13 +020021
Ole Troan1732fc12016-08-30 21:03:51 +020022def eprint(*args, **kwargs):
23 print(*args, file=sys.stderr, **kwargs)
24
Ole Troana03f4ef2016-12-02 12:53:55 +010025class VPP():
26 def __init__(self, apifiles):
27 self.messages = {}
28 self.id_names = []
29 self.id_msgdef = []
30 self.buffersize = 10000
31 self.connected = False
32 self.header = struct.Struct('>HI')
33 self.results = {}
34 self.timeout = 5
35 self.apifile = []
Ole Troan5f9dcff2016-08-01 04:59:13 +020036
Ole Troana03f4ef2016-12-02 12:53:55 +010037 for file in apifiles:
38 self.apifile.append(file)
39 with open(file) as apidef_file:
40 api = json.load(apidef_file)
41 for t in api['types']:
42 self.add_type(t[0], t[1:])
Ole Troan5f9dcff2016-08-01 04:59:13 +020043
Ole Troana03f4ef2016-12-02 12:53:55 +010044 for m in api['messages']:
45 self.add_message(m[0], m[1:])
Ole Troan5f9dcff2016-08-01 04:59:13 +020046
Ole Troana03f4ef2016-12-02 12:53:55 +010047 # Basic sanity check
48 if not 'control_ping' in self.messages:
49 raise ValueError(1, 'Error in JSON message definitions')
Ole Troan5f9dcff2016-08-01 04:59:13 +020050
Ole Troan5f9dcff2016-08-01 04:59:13 +020051
Ole Troana03f4ef2016-12-02 12:53:55 +010052 class ContextId(object):
53 def __init__(self):
54 self.context = 0
55 def __call__(self):
56 self.context += 1
57 return self.context
58 get_context = ContextId()
Ole Troan5f9dcff2016-08-01 04:59:13 +020059
Ole Troana03f4ef2016-12-02 12:53:55 +010060 def status(self):
61 print('Connected') if self.connected else print('Not Connected')
62 print('Read API definitions from', self.apifile)
Ole Troan5f9dcff2016-08-01 04:59:13 +020063
Ole Troana03f4ef2016-12-02 12:53:55 +010064 def __struct (self, t, n = None, e = 0, vl = None):
65 base_types = { 'u8' : 'B',
66 'u16' : 'H',
67 'u32' : 'I',
68 'i32' : 'i',
69 'u64' : 'Q',
70 'f64' : 'd',
71 }
72 pack = None
73 if t in base_types:
74 pack = base_types[t]
75 if not vl:
76 if e and t == 'u8':
77 # Fixed byte array
78 return struct.Struct('>' + str(e) + 's')
79 if e:
80 # Fixed array of base type
81 return [e, struct.Struct('>' + base_types[t])]
82 else:
83 # Variable length array
84 return [vl, struct.Struct('>s')] if t == 'u8' else [vl, struct.Struct('>' + base_types[t])]
Ole Troan57c3d662016-09-12 22:00:32 +020085
Ole Troana03f4ef2016-12-02 12:53:55 +010086 return struct.Struct('>' + base_types[t])
Ole Troan57c3d662016-09-12 22:00:32 +020087
Ole Troana03f4ef2016-12-02 12:53:55 +010088 if t in self.messages:
89 ### Return a list in case of array ###
90 if e and not vl:
91 return [e, lambda self, encode, buf, offset, args: (
92 self.__struct_type(encode, self.messages[t], buf, offset, args)
93 )]
94 if vl:
95 return [vl, lambda self, encode, buf, offset, args: (
96 self.__struct_type(encode, self.messages[t], buf, offset, args)
97 )]
98 return lambda self, encode, buf, offset, args: (
99 self.__struct_type(encode, self.messages[t], buf, offset, args)
100 )
Ole Troanb8602b52016-10-05 11:10:50 +0200101
Ole Troana03f4ef2016-12-02 12:53:55 +0100102 raise ValueError
Ole Troan5f9dcff2016-08-01 04:59:13 +0200103
Ole Troana03f4ef2016-12-02 12:53:55 +0100104 def __struct_type(self, encode, msgdef, buf, offset, kwargs):
105 if encode:
106 return self.__struct_type_encode(msgdef, buf, offset, kwargs)
107 else:
108 return self.__struct_type_decode(msgdef, buf, offset)
Ole Troan5f9dcff2016-08-01 04:59:13 +0200109
Ole Troana03f4ef2016-12-02 12:53:55 +0100110 def __struct_type_encode(self, msgdef, buf, offset, kwargs):
111 off = offset
112 size = 0
Ole Troan7e3a8752016-12-05 10:27:09 +0100113
114 for k in kwargs:
115 if k not in msgdef['args']:
116 raise ValueError(1, 'Invalid field-name in message call ' + k)
117
Ole Troana03f4ef2016-12-02 12:53:55 +0100118 for k,v in msgdef['args'].iteritems():
119 off += size
120 if k in kwargs:
121 if type(v) is list:
122 if callable(v[1]):
123 if v[0] in kwargs:
124 e = kwargs[v[0]]
125 else:
126 e = v[0]
127 size = 0
128 for i in range(e):
129 size += v[1](self, True, buf, off + size,
130 kwargs[k][i])
131 else:
132 if v[0] in kwargs:
133 l = kwargs[v[0]]
134 else:
135 l = len(kwargs[k])
136 if v[1].size == 1:
137 buf[off:off + l] = bytearray(kwargs[k])
138 size = l
139 else:
140 size = 0
141 for i in kwargs[k]:
142 v[1].pack_into(buf, off + size, i)
143 size += v[1].size
144 else:
145 if callable(v):
146 size = v(self, True, buf, off, kwargs[k])
147 else:
148 v.pack_into(buf, off, kwargs[k])
149 size = v.size
150 else:
Ole Troan7e3a8752016-12-05 10:27:09 +0100151 size = v.size if not type(v) is list else 0
Ole Troan5f9dcff2016-08-01 04:59:13 +0200152
Ole Troana03f4ef2016-12-02 12:53:55 +0100153 return off + size - offset
Ole Troan5f9dcff2016-08-01 04:59:13 +0200154
Ole Troan57c3d662016-09-12 22:00:32 +0200155
Ole Troana03f4ef2016-12-02 12:53:55 +0100156 def __getitem__(self, name):
157 if name in self.messages:
158 return self.messages[name]
159 return None
Ole Troan5f9dcff2016-08-01 04:59:13 +0200160
Ole Troana03f4ef2016-12-02 12:53:55 +0100161 def encode(self, msgdef, kwargs):
162 # Make suitably large buffer
163 buf = bytearray(self.buffersize)
164 offset = 0
165 size = self.__struct_type(True, msgdef, buf, offset, kwargs)
166 return buf[:offset + size]
167
168 def decode(self, msgdef, buf):
169 return self.__struct_type(False, msgdef, buf, 0, None)[1]
170
171 def __struct_type_decode(self, msgdef, buf, offset):
172 res = []
173 off = offset
174 size = 0
175 for k,v in msgdef['args'].iteritems():
176 off += size
177 if type(v) is list:
178 lst = []
179 if callable(v[1]): # compound type
180 size = 0
181 if v[0] in msgdef['args']: # vla
182 e = int(res[-1])
183 else: # fixed array
184 e = v[0]
185 res.append(lst)
186 for i in range(e):
187 (s,l) = v[1](self, False, buf, off + size, None)
188 lst.append(l)
189 size += s
190 continue
191
192 if v[1].size == 1:
193 size = int(res[-1])
194 res.append(buf[off:off + size])
195 else:
196 e = int(res[-1])
197 if e == 0:
198 raise ValueError
199 lst = []
200 res.append(lst)
201 size = 0
202 for i in range(e):
203 lst.append(v[1].unpack_from(buf, off + size)[0])
204 size += v[1].size
205 else:
206 if callable(v):
207 (s,l) = v(self, False, buf, off, None)
208 res.append(l)
209 size += s
210 else:
211 res.append(v.unpack_from(buf, off)[0])
212 size = v.size
213
214 return off + size - offset, msgdef['return_tuple']._make(res)
215
216 def ret_tup(self, name):
217 if name in self.messages and 'return_tuple' in self.messages[name]:
218 return self.messages[name]['return_tuple']
219 return None
220
221 def add_message(self, name, msgdef):
222 if name in self.messages:
223 raise ValueError('Duplicate message name: ' + name)
224
225 args = collections.OrderedDict()
226 fields = []
227 msg = {}
228 for f in msgdef:
229 if type(f) is dict and 'crc' in f:
230 msg['crc'] = f['crc']
231 continue
232 field_name = f[1]
233 args[field_name] = self.__struct(*f)
234 fields.append(field_name)
235 msg['return_tuple'] = collections.namedtuple(name, fields,
236 rename = True)
237 self.messages[name] = msg
238 self.messages[name]['args'] = args
239 return self.messages[name]
240
241 def add_type(self, name, typedef):
242 self.add_message('vl_api_' + name + '_t', typedef)
243
Wojciech Dec64bc6122016-12-12 11:32:25 +0100244 def make_function(self, i, msgdef, multipart, async):
245 if (async):
246 return lambda **kwargs: (self._call_vpp_async(i, msgdef, multipart, **kwargs))
247 else:
248 return lambda **kwargs: (self._call_vpp(i, msgdef, multipart, **kwargs))
Ole Troana03f4ef2016-12-02 12:53:55 +0100249
Wojciech Dec64bc6122016-12-12 11:32:25 +0100250 def _register_functions(self, async=False):
Ole Troana03f4ef2016-12-02 12:53:55 +0100251 self.id_names = [None] * (self.vpp_dictionary_maxid + 1)
252 self.id_msgdef = [None] * (self.vpp_dictionary_maxid + 1)
253 for name, msgdef in self.messages.iteritems():
254 if name in self.vpp_dictionary:
255 if self.messages[name]['crc'] != self.vpp_dictionary[name]['crc']:
256 raise ValueError(3, 'Failed CRC checksum ' + name +
257 ' ' + self.messages[name]['crc'] +
258 ' ' + self.vpp_dictionary[name]['crc'])
259 i = self.vpp_dictionary[name]['id']
260 self.id_msgdef[i] = msgdef
261 self.id_names[i] = name
262 multipart = True if name.find('_dump') > 0 else False
Wojciech Dec64bc6122016-12-12 11:32:25 +0100263 setattr(self, name, self.make_function(i, msgdef, multipart, async))
Ole Troana03f4ef2016-12-02 12:53:55 +0100264
265 def _write (self, buf):
266 if not self.connected:
267 raise IOError(1, 'Not connected')
268 return vpp_api.write(str(buf))
269
270 def _load_dictionary(self):
271 self.vpp_dictionary = {}
272 self.vpp_dictionary_maxid = 0
Ole Troana03f4ef2016-12-02 12:53:55 +0100273 d = vpp_api.msg_table()
274
275 if not d:
276 raise IOError(3, 'Cannot get VPP API dictionary')
277 for i,n in d:
278 name, crc = n.rsplit('_', 1)
279 crc = '0x' + crc
280 self.vpp_dictionary[name] = { 'id' : i, 'crc' : crc }
281 self.vpp_dictionary_maxid = max(self.vpp_dictionary_maxid, i)
282
Ole Troan7e3a8752016-12-05 10:27:09 +0100283 def connect(self, name, chroot_prefix = None, async = False):
284 msg_handler = self.msg_handler if not async else self.msg_handler_async
Ole Troana03f4ef2016-12-02 12:53:55 +0100285 if not chroot_prefix:
Ole Troan7e3a8752016-12-05 10:27:09 +0100286 rv = vpp_api.connect(name, msg_handler)
Ole Troana03f4ef2016-12-02 12:53:55 +0100287 else:
Ole Troan7e3a8752016-12-05 10:27:09 +0100288 rv = vpp_api.connect(name, msg_handler, chroot_prefix)
Ole Troana03f4ef2016-12-02 12:53:55 +0100289
290 if rv != 0:
291 raise IOError(2, 'Connect failed')
Ole Troan7e3a8752016-12-05 10:27:09 +0100292 self.connected = True
Ole Troana03f4ef2016-12-02 12:53:55 +0100293
294 self._load_dictionary()
Wojciech Dec64bc6122016-12-12 11:32:25 +0100295 self._register_functions(async=async)
Ole Troana03f4ef2016-12-02 12:53:55 +0100296
297 # Initialise control ping
298 self.control_ping_index = self.vpp_dictionary['control_ping']['id']
299 self.control_ping_msgdef = self.messages['control_ping']
300
Ole Troana03f4ef2016-12-02 12:53:55 +0100301 def disconnect(self):
302 rv = vpp_api.disconnect()
303 return rv
304
305 def results_wait(self, context):
306 return (self.results[context]['e'].wait(self.timeout))
307
308 def results_prepare(self, context):
309 self.results[context] = {}
310 self.results[context]['e'] = threading.Event()
311 self.results[context]['e'].clear()
312 self.results[context]['r'] = []
313
314 def results_clean(self, context):
315 del self.results[context]
316
317 def msg_handler(self, msg):
318 if not msg:
319 eprint('vpp_api.read failed')
320 return
321
322 i, ci = self.header.unpack_from(msg, 0)
323 if self.id_names[i] == 'rx_thread_exit':
324 return;
Ole Troan5f9dcff2016-08-01 04:59:13 +0200325
326 #
Ole Troana03f4ef2016-12-02 12:53:55 +0100327 # Decode message and returns a tuple.
Ole Troan5f9dcff2016-08-01 04:59:13 +0200328 #
Ole Troana03f4ef2016-12-02 12:53:55 +0100329 msgdef = self.id_msgdef[i]
330 if not msgdef:
331 raise IOError(2, 'Reply message undefined')
Ole Troan5f9dcff2016-08-01 04:59:13 +0200332
Ole Troana03f4ef2016-12-02 12:53:55 +0100333 r = self.decode(msgdef, msg)
334 if 'context' in r._asdict():
335 if r.context > 0:
336 context = r.context
Ole Troan5f9dcff2016-08-01 04:59:13 +0200337
Ole Troana03f4ef2016-12-02 12:53:55 +0100338 msgname = type(r).__name__
Ole Troan57c3d662016-09-12 22:00:32 +0200339
Ole Troana03f4ef2016-12-02 12:53:55 +0100340 #
341 # XXX: Call provided callback for event
342 # Are we guaranteed to not get an event during processing of other messages?
343 # How to differentiate what's a callback message and what not? Context = 0?
344 #
345 #if not is_waiting_for_reply():
346 if r.context == 0 and self.event_callback:
347 self.event_callback(msgname, r)
348 return
349
350 #
351 # Collect results until control ping
352 #
353 if msgname == 'control_ping_reply':
354 self.results[context]['e'].set()
355 return
356
357 if not context in self.results:
Ole Troan7e3a8752016-12-05 10:27:09 +0100358 eprint('Not expecting results for this context', context, r)
Ole Troana03f4ef2016-12-02 12:53:55 +0100359 return
360
361 if 'm' in self.results[context]:
362 self.results[context]['r'].append(r)
363 return
364
365 self.results[context]['r'] = r
366 self.results[context]['e'].set()
367
Ole Troan7e3a8752016-12-05 10:27:09 +0100368 def msg_handler_async(self, msg):
369 if not msg:
370 eprint('vpp_api.read failed')
371 return
372
373 i, ci = self.header.unpack_from(msg, 0)
374 if self.id_names[i] == 'rx_thread_exit':
375 return;
376
377 #
378 # Decode message and returns a tuple.
379 #
380 msgdef = self.id_msgdef[i]
381 if not msgdef:
382 raise IOError(2, 'Reply message undefined')
383
384 r = self.decode(msgdef, msg)
385 msgname = type(r).__name__
386
387 self.event_callback(msgname, r)
388
Ole Troana03f4ef2016-12-02 12:53:55 +0100389 def _control_ping(self, context):
390 self._write(self.encode(self.control_ping_msgdef,
391 { '_vl_msg_id' : self.control_ping_index,
392 'context' : context}))
393
394 def _call_vpp(self, i, msgdef, multipart, **kwargs):
395 if not 'context' in kwargs:
396 context = self.get_context()
397 kwargs['context'] = context
398 else:
399 context = kwargs['context']
400 kwargs['_vl_msg_id'] = i
401 b = self.encode(msgdef, kwargs)
402
403 self.results_prepare(context)
Ole Troan399ca1c2016-12-06 23:00:38 +0100404 self._write(b)
Ole Troana03f4ef2016-12-02 12:53:55 +0100405
406 if multipart:
407 self.results[context]['m'] = True
408 self._control_ping(context)
Ole Troana03f4ef2016-12-02 12:53:55 +0100409 self.results_wait(context)
410 r = self.results[context]['r']
411 self.results_clean(context)
412 return r
413
Ole Troan7e3a8752016-12-05 10:27:09 +0100414 def _call_vpp_async(self, i, msgdef, multipart, **kwargs):
415 if not 'context' in kwargs:
416 context = self.get_context()
417 kwargs['context'] = context
418 else:
419 context = kwargs['context']
420 kwargs['_vl_msg_id'] = i
421 b = self.encode(msgdef, kwargs)
422
423 self._write(b)
424
Ole Troana03f4ef2016-12-02 12:53:55 +0100425 def register_event_callback(self, callback):
426 self.event_callback = callback
427