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',
40 # NB: If new types are introduced in vpe.api, these must be updated.
48 'vl_api_ip4_fib_counter_t' : 21,
49 'vl_api_ip6_fib_counter_t' : 33,
56 argslist.append(i[1][1:])
70 if len(i) is 3 or len(i) is 4: # TODO: add support for variable length arrays (VPP-162)
71 size = type_size[i[0]]
72 bytecount += size * int(i[2])
73 # Check if we have a zero length array
75 tup += 'msg[' + str(bytecount) + ':],'
81 tup += 'tr[' + str(j) + '],'
83 pack += format_struct[i[0]] * int(i[2])
84 tup += 'tr[' + str(j) + ':' + str(j + int(i[2])) + '],'
87 bytecount += type_size[i[0]]
88 pack += format_struct[i[0]]
89 tup += 'tr[' + str(j) + '],'
90 return pack, bytecount, tup, zeroarray
92 def get_reply_func(f):
93 if f['name']+'_reply' in func_name:
94 return func_name[f['name']+'_reply']
95 if f['name'].find('_dump') > 0:
96 r = f['name'].replace('_dump','_details')
102 # Read enums from stdin
107 l = l.replace(',\n','')
110 l = l.replace('VL_API_','').lower()
112 enums_by_index[i] = l
115 return enums_by_name, enums_by_index
117 def get_definitions():
122 for a in cfg.vppapidef:
123 pack, packlen, tup, zeroarray = get_pack(a[1:])
124 func_name[a[0]] = dict([('name', a[0]), ('pack', pack), ('packlen', packlen), ('tup', tup), ('args', get_args(a[1:])),
125 ('zeroarray', zeroarray)])
126 func_list.append(func_name[a[0]]) # Indexed by name
127 return func_list, func_name
129 def generate_c_macros(func_list, enums_by_name):
130 file = open(args.cfile, 'w+')
131 print >>file, "#define foreach_api_msg \\"
133 if not f['name'] in enums_by_name:
135 print >>file, "_(" + f['name'].upper() + ", " + f['name'] + ") \\"
137 void pneum_set_handlers(void) {
139 api_func_table[VL_API_##N] = sizeof(vl_api_##n##_t);
146 # Print array with a hash of 'decode' and 'multipart'
147 # Simplify to do only decode for now. And deduce multipart from _dump?
149 def decode_function_print(name, args, pack, packlen, tup):
151 print(u'def ' + name + u'_decode(msg):')
152 print(u" n = namedtuple('" + name + "', '" + ', '.join(args) + "')" +
157 print(u" tr = unpack('" + pack + "', msg[:" + str(packlen) + "])")
158 print(u" r = n._make((" + tup + "))" +
165 def function_print(name, id, args, pack, multipart, zeroarray):
167 print "def", name + "(async = False):"
169 print "def", name + "(" + ', '.join(args[3:]) + ", async = False):"
170 print " global waiting_for_reply"
171 print " context = get_context(" + id + ")"
174 results[context] = {}
175 results[context]['e'] = threading.Event()
176 results[context]['e'].clear()
177 results[context]['r'] = []
178 waiting_for_reply = True
180 if multipart == True:
181 print " results[context]['m'] = True"
183 if zeroarray == True:
184 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:-1]) + ") + " + args[-1] + ")"
186 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:]) + "))"
188 if multipart == True:
189 print " vpp_api.write(pack('>HII', VL_API_CONTROL_PING, 0, context))"
193 results[context]['e'].wait(5)
194 return results[context]['r']
199 # Should dynamically create size
201 def api_table_print (name, msg_id):
203 print('api_func_table[' + msg_id + '] = ' + f)
206 # Generate the main Python file
212 # AUTO-GENERATED FILE. PLEASE DO NOT EDIT.
214 import sys, time, threading, signal, os, logging
216 from collections import namedtuple
219 # Import C API shared object
225 waiting_for_reply = False
228 # XXX: Make this return a unique number
235 def msg_handler(msg):
236 global result, context, event_callback, waiting_for_reply
238 logging.warning('vpp_api.read failed')
241 id = unpack('>H', msg[0:2])
242 logging.debug('Received message', id[0])
243 if id[0] == VL_API_RX_THREAD_EXIT:
244 logging.info("We got told to leave")
248 # Decode message and returns a tuple.
250 logging.debug('api_func', api_func_table[id[0]])
251 r = api_func_table[id[0]](msg)
253 logging.warning('Message decode failed', id[0])
256 if 'context' in r._asdict():
261 # XXX: Call provided callback for event
262 # Are we guaranteed to not get an event during processing of other messages?
263 # How to differentiate what's a callback message and what not? Context = 0?
265 logging.debug('R:', context, r, waiting_for_reply)
266 if waiting_for_reply == False:
271 # Collect results until control ping
273 if id[0] == VL_API_CONTROL_PING_REPLY:
274 results[context]['e'].set()
275 waiting_for_reply = False
277 if not context in results:
278 logging.warning('Not expecting results for this context', context)
280 if 'm' in results[context]:
281 results[context]['r'].append(r)
284 results[context]['r'] = r
285 results[context]['e'].set()
286 waiting_for_reply = False
289 signal.alarm(3) # 3 second
290 rv = vpp_api.connect(name, msg_handler)
292 logging.info("Connect:", rv)
296 rv = vpp_api.disconnect()
297 logging.info("Disconnected")
300 def register_event_callback(callback):
301 global event_callback
302 event_callback = callback
305 enums_by_name, enums_by_index = get_enums()
306 func_list, func_name = get_definitions()
309 # Not needed with the new msg_size field.
310 # generate_c_macros(func_list, enums_by_name)
313 pp = pprint.PrettyPrinter(indent=4)
314 #print 'enums_by_index =', pp.pprint(enums_by_index)
315 #print 'func_name =', pp.pprint(func_name)
320 # 1) The VPE API lacks a clear definition of what messages are reply messages
321 # 2) Length is missing, and has to be pre-known or in case of variable sized ones calculated per message type
324 #if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
325 decode_function_print(f['name'], f['args'], f['pack'], f['packlen'], f['tup'])
327 #r = get_reply_func(f)
330 # # XXX: Functions here are not taken care of. E.g. events
332 # print('Missing function', f)
335 if f['name'].find('_dump') > 0:
336 f['multipart'] = True
338 f['multipart'] = False
339 msg_id_in = 'VL_API_' + f['name'].upper()
340 function_print(f['name'], msg_id_in, f['args'], f['pack'], f['multipart'], f['zeroarray'])
343 print "api_func_table = [0] * 10000"
345 # if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
346 msg_id_in = 'VL_API_' + f['name'].upper()
347 api_table_print(f['name'], msg_id_in)