blob: 27d4315aae40dbe9fcb9eddf0eb75598e2e15fca [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
244 def make_function(self, i, msgdef, multipart):
245 return lambda **kwargs: (self._call_vpp(i, msgdef, multipart, **kwargs))
246
247 def _register_functions(self):
248 self.id_names = [None] * (self.vpp_dictionary_maxid + 1)
249 self.id_msgdef = [None] * (self.vpp_dictionary_maxid + 1)
250 for name, msgdef in self.messages.iteritems():
251 if name in self.vpp_dictionary:
252 if self.messages[name]['crc'] != self.vpp_dictionary[name]['crc']:
253 raise ValueError(3, 'Failed CRC checksum ' + name +
254 ' ' + self.messages[name]['crc'] +
255 ' ' + self.vpp_dictionary[name]['crc'])
256 i = self.vpp_dictionary[name]['id']
257 self.id_msgdef[i] = msgdef
258 self.id_names[i] = name
259 multipart = True if name.find('_dump') > 0 else False
260 setattr(self, name, self.make_function(i, msgdef, multipart))
261
262 def _write (self, buf):
263 if not self.connected:
264 raise IOError(1, 'Not connected')
265 return vpp_api.write(str(buf))
266
267 def _load_dictionary(self):
268 self.vpp_dictionary = {}
269 self.vpp_dictionary_maxid = 0
Ole Troana03f4ef2016-12-02 12:53:55 +0100270 d = vpp_api.msg_table()
271
272 if not d:
273 raise IOError(3, 'Cannot get VPP API dictionary')
274 for i,n in d:
275 name, crc = n.rsplit('_', 1)
276 crc = '0x' + crc
277 self.vpp_dictionary[name] = { 'id' : i, 'crc' : crc }
278 self.vpp_dictionary_maxid = max(self.vpp_dictionary_maxid, i)
279
Ole Troan7e3a8752016-12-05 10:27:09 +0100280 def connect(self, name, chroot_prefix = None, async = False):
281 msg_handler = self.msg_handler if not async else self.msg_handler_async
Ole Troana03f4ef2016-12-02 12:53:55 +0100282 if not chroot_prefix:
Ole Troan7e3a8752016-12-05 10:27:09 +0100283 rv = vpp_api.connect(name, msg_handler)
Ole Troana03f4ef2016-12-02 12:53:55 +0100284 else:
Ole Troan7e3a8752016-12-05 10:27:09 +0100285 rv = vpp_api.connect(name, msg_handler, chroot_prefix)
Ole Troana03f4ef2016-12-02 12:53:55 +0100286
287 if rv != 0:
288 raise IOError(2, 'Connect failed')
Ole Troan7e3a8752016-12-05 10:27:09 +0100289 self.connected = True
Ole Troana03f4ef2016-12-02 12:53:55 +0100290
291 self._load_dictionary()
292 self._register_functions()
293
294 # Initialise control ping
295 self.control_ping_index = self.vpp_dictionary['control_ping']['id']
296 self.control_ping_msgdef = self.messages['control_ping']
297
Ole Troana03f4ef2016-12-02 12:53:55 +0100298 def disconnect(self):
299 rv = vpp_api.disconnect()
300 return rv
301
302 def results_wait(self, context):
303 return (self.results[context]['e'].wait(self.timeout))
304
305 def results_prepare(self, context):
306 self.results[context] = {}
307 self.results[context]['e'] = threading.Event()
308 self.results[context]['e'].clear()
309 self.results[context]['r'] = []
310
311 def results_clean(self, context):
312 del self.results[context]
313
314 def msg_handler(self, msg):
315 if not msg:
316 eprint('vpp_api.read failed')
317 return
318
319 i, ci = self.header.unpack_from(msg, 0)
320 if self.id_names[i] == 'rx_thread_exit':
321 return;
Ole Troan5f9dcff2016-08-01 04:59:13 +0200322
323 #
Ole Troana03f4ef2016-12-02 12:53:55 +0100324 # Decode message and returns a tuple.
Ole Troan5f9dcff2016-08-01 04:59:13 +0200325 #
Ole Troana03f4ef2016-12-02 12:53:55 +0100326 msgdef = self.id_msgdef[i]
327 if not msgdef:
328 raise IOError(2, 'Reply message undefined')
Ole Troan5f9dcff2016-08-01 04:59:13 +0200329
Ole Troana03f4ef2016-12-02 12:53:55 +0100330 r = self.decode(msgdef, msg)
331 if 'context' in r._asdict():
332 if r.context > 0:
333 context = r.context
Ole Troan5f9dcff2016-08-01 04:59:13 +0200334
Ole Troana03f4ef2016-12-02 12:53:55 +0100335 msgname = type(r).__name__
Ole Troan57c3d662016-09-12 22:00:32 +0200336
Ole Troana03f4ef2016-12-02 12:53:55 +0100337 #
338 # XXX: Call provided callback for event
339 # Are we guaranteed to not get an event during processing of other messages?
340 # How to differentiate what's a callback message and what not? Context = 0?
341 #
342 #if not is_waiting_for_reply():
343 if r.context == 0 and self.event_callback:
344 self.event_callback(msgname, r)
345 return
346
347 #
348 # Collect results until control ping
349 #
350 if msgname == 'control_ping_reply':
351 self.results[context]['e'].set()
352 return
353
354 if not context in self.results:
Ole Troan7e3a8752016-12-05 10:27:09 +0100355 eprint('Not expecting results for this context', context, r)
Ole Troana03f4ef2016-12-02 12:53:55 +0100356 return
357
358 if 'm' in self.results[context]:
359 self.results[context]['r'].append(r)
360 return
361
362 self.results[context]['r'] = r
363 self.results[context]['e'].set()
364
Ole Troan7e3a8752016-12-05 10:27:09 +0100365 def msg_handler_async(self, msg):
366 if not msg:
367 eprint('vpp_api.read failed')
368 return
369
370 i, ci = self.header.unpack_from(msg, 0)
371 if self.id_names[i] == 'rx_thread_exit':
372 return;
373
374 #
375 # Decode message and returns a tuple.
376 #
377 msgdef = self.id_msgdef[i]
378 if not msgdef:
379 raise IOError(2, 'Reply message undefined')
380
381 r = self.decode(msgdef, msg)
382 msgname = type(r).__name__
383
384 self.event_callback(msgname, r)
385
Ole Troana03f4ef2016-12-02 12:53:55 +0100386 def _control_ping(self, context):
387 self._write(self.encode(self.control_ping_msgdef,
388 { '_vl_msg_id' : self.control_ping_index,
389 'context' : context}))
390
391 def _call_vpp(self, i, msgdef, multipart, **kwargs):
392 if not 'context' in kwargs:
393 context = self.get_context()
394 kwargs['context'] = context
395 else:
396 context = kwargs['context']
397 kwargs['_vl_msg_id'] = i
398 b = self.encode(msgdef, kwargs)
399
400 self.results_prepare(context)
Ole Troan399ca1c2016-12-06 23:00:38 +0100401 self._write(b)
Ole Troana03f4ef2016-12-02 12:53:55 +0100402
403 if multipart:
404 self.results[context]['m'] = True
405 self._control_ping(context)
Ole Troana03f4ef2016-12-02 12:53:55 +0100406 self.results_wait(context)
407 r = self.results[context]['r']
408 self.results_clean(context)
409 return r
410
Ole Troan7e3a8752016-12-05 10:27:09 +0100411 def _call_vpp_async(self, i, msgdef, multipart, **kwargs):
412 if not 'context' in kwargs:
413 context = self.get_context()
414 kwargs['context'] = context
415 else:
416 context = kwargs['context']
417 kwargs['_vl_msg_id'] = i
418 b = self.encode(msgdef, kwargs)
419
420 self._write(b)
421
Ole Troana03f4ef2016-12-02 12:53:55 +0100422 def register_event_callback(self, callback):
423 self.event_callback = callback
424