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,
55 argslist.append(i[1].replace('_',''))
67 size = type_size[i[0]]
68 bytecount += size * int(i[2])
69 # Check if we have a zero length array
71 tup += 'msg[' + str(bytecount) + ':],'
77 tup += 'tr[' + str(j) + '],'
79 pack += format_struct[i[0]] * int(i[2])
80 tup += 'tr[' + str(j) + ':' + str(j + int(i[2])) + '],'
83 bytecount += type_size[i[0]]
84 pack += format_struct[i[0]]
85 tup += 'tr[' + str(j) + '],'
86 return pack, bytecount, tup, zeroarray
88 def get_reply_func(f):
89 if f['name']+'_reply' in func_name:
90 return func_name[f['name']+'_reply']
91 if f['name'].find('_dump') > 0:
92 r = f['name'].replace('_dump','_details')
98 # Read enums from stdin
103 l = l.replace(',\n','')
106 l = l.replace('VL_API_','').lower()
108 enums_by_index[i] = l
111 return enums_by_name, enums_by_index
113 def get_definitions():
118 for a in cfg.vppapidef:
119 pack, packlen, tup, zeroarray = get_pack(a[1:])
120 func_name[a[0]] = dict([('name', a[0]), ('pack', pack), ('packlen', packlen), ('tup', tup), ('args', get_args(a[1:])),
121 ('zeroarray', zeroarray)])
122 func_list.append(func_name[a[0]]) # Indexed by name
123 return func_list, func_name
125 def generate_c_macros(func_list, enums_by_name):
126 file = open(args.cfile, 'w+')
127 print >>file, "#define foreach_api_msg \\"
129 if not f['name'] in enums_by_name:
131 print >>file, "_(" + f['name'].upper() + ", " + f['name'] + ") \\"
133 void pneum_set_handlers(void) {
135 api_func_table[VL_API_##N] = sizeof(vl_api_##n##_t);
142 # Print array with a hash of 'decode' and 'multipart'
143 # Simplify to do only decode for now. And deduce multipart from _dump?
145 def decode_function_print(name, args, pack, packlen, tup):
147 print(u'def ' + name + u'_decode(msg):')
148 print(u" n = namedtuple('" + name + "', '" + ', '.join(args) + "')" +
153 print(u" tr = unpack('" + pack + "', msg[:" + str(packlen) + "])")
154 print(u" r = n._make((" + tup + "))" +
161 def function_print(name, id, args, pack, multipart, zeroarray):
163 print "def", name + "(async = False):"
165 print "def", name + "(" + ', '.join(args[3:]) + ", 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 if zeroarray == True:
180 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:-1]) + ") + " + args[-1] + ")"
182 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:]) + "))"
184 if multipart == True:
185 print " vpp_api.write(pack('>HII', VL_API_CONTROL_PING, 0, context))"
189 results[context]['e'].wait(5)
190 return results[context]['r']
195 # Should dynamically create size
197 def api_table_print (name, msg_id):
199 print('api_func_table[' + msg_id + '] = ' + f)
202 # Generate the main Python file
205 print '''#!/usr/bin/env python3
208 # AUTO-GENERATED FILE. PLEASE DO NOT EDIT.
210 import sys, time, threading, signal, os, logging
212 from collections import namedtuple
215 # Import C API shared object
221 waiting_for_reply = False
224 # XXX: Make this return a unique number
231 def msg_handler(msg):
232 global result, context, event_callback, waiting_for_reply
234 logging.warning('vpp_api.read failed')
237 id = unpack('>H', msg[0:2])
238 logging.debug('Received message', id[0])
239 if id[0] == VL_API_RX_THREAD_EXIT:
240 logging.info("We got told to leave")
244 # Decode message and returns a tuple.
246 logging.debug('api_func', api_func_table[id[0]])
247 r = api_func_table[id[0]](msg)
249 logging.warning('Message decode failed', id[0])
252 if 'context' in r._asdict():
257 # XXX: Call provided callback for event
258 # Are we guaranteed to not get an event during processing of other messages?
259 # How to differentiate what's a callback message and what not? Context = 0?
261 logging.debug('R:', context, r, waiting_for_reply)
262 if waiting_for_reply == False:
267 # Collect results until control ping
269 if id[0] == VL_API_CONTROL_PING_REPLY:
270 results[context]['e'].set()
271 waiting_for_reply = False
273 if not context in results:
274 logging.warning('Not expecting results for this context', context)
276 if 'm' in results[context]:
277 results[context]['r'].append(r)
280 results[context]['r'] = r
281 results[context]['e'].set()
282 waiting_for_reply = False
285 signal.alarm(3) # 3 second
286 rv = vpp_api.connect(name, msg_handler)
288 logging.info("Connect:", rv)
292 rv = vpp_api.disconnect()
293 logging.info("Disconnected")
296 def register_event_callback(callback):
297 global event_callback
298 event_callback = callback
301 enums_by_name, enums_by_index = get_enums()
302 func_list, func_name = get_definitions()
305 # Not needed with the new msg_size field.
306 # generate_c_macros(func_list, enums_by_name)
309 pp = pprint.PrettyPrinter(indent=4)
310 #print 'enums_by_index =', pp.pprint(enums_by_index)
311 #print 'func_name =', pp.pprint(func_name)
316 # 1) The VPE API lacks a clear definition of what messages are reply messages
317 # 2) Length is missing, and has to be pre-known or in case of variable sized ones calculated per message type
320 #if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
321 decode_function_print(f['name'], f['args'], f['pack'], f['packlen'], f['tup'])
323 #r = get_reply_func(f)
326 # # XXX: Functions here are not taken care of. E.g. events
328 # print('Missing function', f)
331 if f['name'].find('_dump') > 0:
332 f['multipart'] = True
334 f['multipart'] = False
335 msg_id_in = 'VL_API_' + f['name'].upper()
336 function_print(f['name'], msg_id_in, f['args'], f['pack'], f['multipart'], f['zeroarray'])
339 print "api_func_table = [0] * 10000"
341 # if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
342 msg_id_in = 'VL_API_' + f['name'].upper()
343 api_table_print(f['name'], msg_id_in)