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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 import argparse, sys, os, importlib, pprint
19 parser = argparse.ArgumentParser(description='VPP Python API generator')
20 parser.add_argument('-i', action="store", dest="inputfile")
21 parser.add_argument('-c', '--cfile', action="store")
22 args = parser.parse_args()
26 inputfile = args.inputfile.replace('.py', '')
27 cfg = importlib.import_module(inputfile, package=None)
29 # https://docs.python.org/3/library/struct.html
30 format_struct = {'u8': 'B',
36 'vl_api_ip4_fib_counter_t' : 'IBQQ',
37 'vl_api_ip6_fib_counter_t' : 'QQBQQ',
45 'vl_api_ip4_fib_counter_t' : 21,
46 'vl_api_ip6_fib_counter_t' : 33,
53 arg = arg.replace('_','')
57 args = args + ', ' + arg
68 size = type_size[i[0]]
69 bytecount += size * int(i[2])
71 tup += 'msg[' + str(bytecount) + ':],'
76 tup += 'tr[' + str(j) + '],'
78 pack += format_struct[i[0]] * int(i[2])
79 tup += 'tr[' + str(j) + ':' + str(j + int(i[2])) + '],'
82 bytecount += type_size[i[0]]
83 pack += format_struct[i[0]]
84 tup += 'tr[' + str(j) + '],'
85 return pack, bytecount, tup
87 def get_reply_func(f):
88 if f['name']+'_reply' in func_name:
89 return func_name[f['name']+'_reply']
90 if f['name'].find('_dump') > 0:
91 r = f['name'].replace('_dump','_details')
97 # Read enums from stdin
102 l = l.replace(',\n','')
105 l = l.replace('VL_API_','').lower()
107 enums_by_index[i] = l
110 return enums_by_name, enums_by_index
112 def get_definitions():
117 for a in cfg.vppapidef:
118 pack, packlen, tup = get_pack(a[1:])
119 func_name[a[0]] = dict([('name', a[0]), ('args', get_args(a[4:])), ('full_args', get_args(a[1:])), ('pack', pack), ('packlen', packlen), ('tup', tup)])
120 func_list.append(func_name[a[0]]) # Indexed by name
121 return func_list, func_name
123 def generate_c_macros(func_list, enums_by_name):
124 file = open(args.cfile, 'w+')
125 print >>file, "#define foreach_api_msg \\"
127 if not f['name'] in enums_by_name:
129 print >>file, "_(" + f['name'].upper() + ", " + f['name'] + ") \\"
131 void pneum_set_handlers(void) {
133 api_func_table[VL_API_##N] = sizeof(vl_api_##n##_t);
140 # XXX:Deal with empty arrays
141 # Print array with a hash of 'decode' and 'multipart'
142 # Simplify to do only decode for now. And deduce multipart from _dump?
144 def decode_function_print(name, args, pack, packlen, tup):
146 print(u'def ' + name + u'_decode(msg):')
147 print(u" n = namedtuple('" + name + "', '" + args + "')" +
152 print(u" tr = unpack('" + pack + "', msg[:" + str(packlen) + "])")
153 print(u" r = n._make((" + tup + "))" +
160 def function_print(name, id, args, pack, multipart):
163 print "def", name + "(async = False):"
165 print "def", name + "(" + args + ",async = False):"
166 print " global waiting_for_reply"
167 print " context = get_context(" + id + ")"
170 results[context] = {}
171 results[context]['e'] = threading.Event()
172 results[context]['e'].clear()
173 results[context]['r'] = []
174 waiting_for_reply = True
176 if multipart == True:
177 print " results[context]['m'] = True"
179 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + args + "))"
181 if multipart == True:
182 print " vpp_api.write(pack('>HII', VL_API_CONTROL_PING, 0, context))"
186 results[context]['e'].wait(5)
187 return results[context]['r']
192 # Should dynamically create size
194 def api_table_print (name, msg_id):
196 print('api_func_table[' + msg_id + '] = ' + f)
199 # Generate the main Python file
202 print '''#!/usr/bin/env python3
204 import sys, time, threading, signal, os, logging
206 from collections import namedtuple
209 # Import C API shared object
215 waiting_for_reply = False
218 # XXX: Make this return a unique number
225 def msg_handler(msg):
226 global result, context, event_callback, waiting_for_reply
228 logging.warning('vpp_api.read failed')
231 id = unpack('>H', msg[0:2])
232 logging.debug('Received message', id[0])
233 if id[0] == VL_API_RX_THREAD_EXIT:
234 logging.info("We got told to leave")
238 # Decode message and returns a tuple.
240 logging.debug('api_func', api_func_table[id[0]])
241 r = api_func_table[id[0]](msg)
243 logging.warning('Message decode failed', id[0])
246 if 'context' in r._asdict():
251 # XXX: Call provided callback for event
252 # Are we guaranteed to not get an event during processing of other messages?
253 # How to differentiate what's a callback message and what not? Context = 0?
255 logging.debug('R:', context, r, waiting_for_reply)
256 if waiting_for_reply == False:
261 # Collect results until control ping
263 if id[0] == VL_API_CONTROL_PING_REPLY:
264 results[context]['e'].set()
265 waiting_for_reply = False
267 if not context in results:
268 logging.warning('Not expecting results for this context', context)
270 if 'm' in results[context]:
271 results[context]['r'].append(r)
274 results[context]['r'] = r
275 results[context]['e'].set()
276 waiting_for_reply = False
279 signal.alarm(3) # 3 second
280 rv = vpp_api.connect(name, msg_handler)
282 logging.info("Connect:", rv)
286 rv = vpp_api.disconnect()
287 logging.info("Disconnected")
290 def register_event_callback(callback):
291 global event_callback
292 event_callback = callback
295 enums_by_name, enums_by_index = get_enums()
296 func_list, func_name = get_definitions()
299 # Not needed with the new msg_size field.
300 # generate_c_macros(func_list, enums_by_name)
303 pp = pprint.PrettyPrinter(indent=4)
304 #print 'enums_by_index =', pp.pprint(enums_by_index)
305 #print 'func_name =', pp.pprint(func_name)
310 # 1) The VPE API lacks a clear definition of what messages are reply messages
311 # 2) Length is missing, and has to be pre-known or in case of variable sized ones calculated per message type
314 #if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
315 decode_function_print(f['name'], f['full_args'], f['pack'], f['packlen'], f['tup'])
317 #r = get_reply_func(f)
320 # # XXX: Functions here are not taken care of. E.g. events
322 # print('Missing function', f)
325 if f['name'].find('_dump') > 0:
326 f['multipart'] = True
328 f['multipart'] = False
329 msg_id_in = 'VL_API_' + f['name'].upper()
330 function_print(f['name'], msg_id_in, f['args'], f['pack'], f['multipart'])
333 print "api_func_table = [0] * 10000"
335 # if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
336 msg_id_in = 'VL_API_' + f['name'].upper()
337 api_table_print(f['name'], msg_id_in)